Quant Christo
Quant Christo

Reputation: 1430

Dataframe transpose - how to get columns name right?

I have dataframe like this:

import pandas as pd
df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'ent':['A','B']})

|   |a  |b   |ent 
|---|---|----|----
|0  |1  |3   |A   
|1  |2  |4   |B   

I want to have this dataframe in form like this:

|ent  |A  |B
-------------
|a    |1  |2
|b    |3  |4

I can apply df.T or df.transpose but I don't get exactly what I want (header):

|     |0  |1
-------------
|a    |1  |2
|b    |3  |4
|ent  |A  |B

I'm looking for pandastic solution (renaming columns and dropping ent row after transpose for me is inelegant).

Upvotes: 3

Views: 4488

Answers (2)

pythonic833
pythonic833

Reputation: 3224

pd.pivot_table(df, values=['a','b'], columns='ent')

does exactly what you want

Edit: jezrael is totally correct. The output of the displayed pivot_table function with

df= a b ent 0 1 3 A 1 2 4 B

is

ent A B a 1 2 b 3 4

but if we change df to

df= a b ent 0 1 3 A 1 2 4 A

the output of pd.pivot_table(df, values=['a','b'], columns='ent') is

ent A a 1.5 b 3.5.

Note that it is possible to apply an own function in the pivot_table argument aggfunc. 'mean' is just the default value.

Upvotes: 1

jezrael
jezrael

Reputation: 862511

If need first column is index add set_index:

df1 = df.set_index('ent').T
print (df1)
ent  A  B
a    1  2
b    3  4

And if need default index:

df1 = df.set_index('ent').T.rename_axis(None, 1).rename_axis('ent').reset_index()
print (df1)
  ent  A  B
0   a  1  2
1   b  3  4

Upvotes: 4

Related Questions