2

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?

2
  • I'm sorry but I can't see the pattern here. How exactly are the elements of the resulting matrix related to the original? Commented Nov 23, 2016 at 23:21
  • Suppose 'b' column shows blood pressure readings and 'a' column shows the patient id. I'd like to have all the readings from each patient in one line. Each patient may have from 1 to a maximum number of readings, say 10. So the final table will be of shape number_of_patients x 10. Commented Nov 23, 2016 at 23:26

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Great solution. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.