Bernando Purba
Bernando Purba

Reputation: 551

Transposing a specific column into row in python dataframe

I try to transpose a dataframe with a specific format : Here is my current dataframe called df : enter image description here

and the result of transpose shoud be : enter image description here

Thanks in advance.

Upvotes: 1

Views: 5219

Answers (2)

BENY
BENY

Reputation: 323226

Assuming you have following dataframe , using 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

Upvotes: 2

jpp
jpp

Reputation: 164673

You can try using pd.pivot_table:

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

If you need to elevate index to columns, reset index via res.reset_index().

Upvotes: 2

Related Questions