How Do I Stack Rows In A Pandas Data Frame To Get One "long Row"?
Let's say I have a data frame with 4 rows, 3 columns. I'd like to stack the rows horizontally so that I get one row with 12 columns. How to do it and how to handle colliding column
Solution 1:
You can achieve this by stacking the frame to produce a series of all the values, we then want to convert this back to a df using to_frame and then reset_index to drop the index levels and then transpose using .T:
In [2]:
df = pd.DataFrame(np.random.randn(4,3), columns=list('abc'))
df
Out[2]:
          a         b         c
0 -1.744219 -2.475923  1.794151
1  0.952148 -0.783606  0.784224
2  0.386506 -0.242355 -0.799157
3 -0.547648 -0.139976 -0.717316
In [3]:
df.stack().to_frame().reset_index(drop=True).T
Out[3]:
         0         1         2         3         4         5         6   \
0 -1.744219 -2.475923  1.794151  0.952148 -0.783606  0.784224  0.386506   
         7         8         9         10        11  
0 -0.242355 -0.799157 -0.547648 -0.139976 -0.717316  
Post a Comment for "How Do I Stack Rows In A Pandas Data Frame To Get One "long Row"?"