Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

python - How to reshape a multi-column dataframe by index?

Following from here . The solution works for only one column. How to improve the solution for multiple columns. i.e If I have a dataframe like

df= pd.DataFrame([['a','b'],['b','c'],['c','z'],['d','b']],index=[0,0,1,1])
   0  1
0  a  b
0  b  c
1  c  z
1  d  b

How to reshape them like

  0   1  2  3
0  a  b  b  c 
1  c  z  d  b

If df is

   0  1
0  a  b
1  c  z
1  d  b

Then

   0  1   2  3
0  a  b NaN  NaN
1  c  z   d  b

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use flatten/ravel

In [4401]: df.groupby(level=0).apply(lambda x: pd.Series(x.values.flatten()))
Out[4401]:
   0  1  2  3
0  a  b  b  c
1  c  z  d  b

Or, stack

In [4413]: df.groupby(level=0).apply(lambda x: pd.Series(x.stack().values))
Out[4413]:
   0  1  2  3
0  a  b  b  c
1  c  z  d  b

Also, with unequal indices

In [4435]: df.groupby(level=0).apply(lambda x: x.values.ravel()).apply(pd.Series)
Out[4435]:
   0  1    2    3
0  a  b  NaN  NaN
1  c  z    d    b

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...