将特定列转换为python数据帧中的行

时间:2018-05-22 01:04:52

标签: python python-3.x pandas dataframe

我尝试使用特定格式转置数据框: 这是我当前的数据框,名为df: enter image description here

转置的结果应该是: enter image description here

提前致谢。

2 个答案:

答案 0 :(得分:2)

假设您有以下数据框,请使用unstack

df=pd.DataFrame({'pid':[1,1,1],'TreeFeature':['a','b','c'],'Import':[1,2,3],'acc':[1,1,1]})
df.set_index(['pid','acc','TreeFeature']).Import.unstack().reset_index()
Out[298]: 
TreeFeature  pid  acc  a  b  c
0              1    1  1  2  3

答案 1 :(得分:1)

您可以尝试使用pd.pivot_table

res = df.pivot_table(index=['pid', 'Accuracy'], columns=['TreeFeatures'],
                     values='Importance 1', aggfunc='first', fill_value=0)

如果您需要将索引提升为列,请通过res.reset_index()重置索引。

相关问题