Reputation: 1430
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
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