如何在Pandas数据帧中堆叠行以获得一个“长行”? [英] How do I stack rows in a Pandas data frame to get one "long row"?

查看:151
本文介绍了如何在Pandas数据帧中堆叠行以获得一个“长行”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个4行,3列的数据框。我想水平堆叠这些行,以便我得到一行12列。

解决方案

你可以通过 stack 创建一系列所有值,然后我们要使用 to_frame 然后 reset_index 删除索引级别,然后使用 .T 进行转置:

 在[2]中:
df = pd.DataFrame(np.random.randn(4,3),columns = list('abc'))
df

出[2]:
abc
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

在[3]中:
df.stack()。to_frame()。reset_index(drop = True).T

输出[ 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


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 names?

解决方案

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  

这篇关于如何在Pandas数据帧中堆叠行以获得一个“长行”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆