user2725109 user2725109 - 12 days ago 5
Python Question

pandas dataframe reshape / pivot

I'd like to convert the following pandas dataframe

a b
0 1 2
1 1 5
2 2 4
3 1 3
4 3 7
5 2 1


to

0 1 2
a
1 2 5 3
2 4 1 NaN
3 7 NaN NaN


Do you know an easy way?

Answer

I would do this as follows:

In [11]: df.groupby("a")["b"].apply(lambda x: pd.Series(x.values))
Out[11]:
a
1  0    2
   1    5
   2    3
2  0    4
   1    1
3  0    7
Name: b, dtype: int64

to get the form you wanted you then unstack (though probably above better):

In [22]: df.groupby('a')["b"].apply(lambda x: pd.Series(x.values)).unstack(1)
Out[22]:
     0    1    2
a
1  2.0  5.0  3.0
2  4.0  1.0  NaN
3  7.0  NaN  NaN