Reputation: 3677
I have a df that looks like this:
Id field value
0 1 first_name a
1 1 number 123
2 1 last_name aa
0 2 first_name b
1 2 number 456
2 2 last_name bb
3 2 type p
Each Id has a different length of index and roughly the same field types but some have more some have less.
How do I flip the df so that fields are columns and values are underneath them?
Like so:
Id first_name number last_name type
0 1 a 123 aa
1 2 b 456 bb p
Upvotes: 1
Views: 117
Reputation: 59579
This is also just .pivot
df.pivot(index='Id', columns='field', values='value').reset_index()
#field Id first_name last_name number type
#0 1 a aa 123 NaN
#1 2 b bb 456 p
If you get ValueError, this likely means that you have a row duplicated on ['Id', 'field']
. This will make it work, but will chose the value as whichever row appears first in your DataFrame
.
pd.pivot_table(df, index='Id', columns='field', values='value', aggfunc='first')
Upvotes: 2
Reputation: 51165
I think you want to set_index
and unstack
:
out = df.set_index(['Id', 'field']).unstack()
out.columns = out.columns.get_level_values(1)
out.reset_index()
field Id first_name last_name number type
0 1 a aa 123 NaN
1 2 b bb 456 p
Upvotes: 3