高效扁平化 pandas 数据框 [英] Efficient flattening of a pandas dataframe

查看:86
本文介绍了高效扁平化 pandas 数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个熊猫数据框.看起来像这样:

I have a pandas dataframe. It looks like this:

pd.DataFrame(data=np.arange(1,10).reshape(3,3), index=['A', 'B', 'C'], columns=['A', 'B', 'C'])

但是有100行和100列.

but has 100 rows and 100 columns.

我想弄平它,使其看起来像这样:

I want to flatten it, so that it looks like this:

pd.DataFrame({'row' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'], 'col' : ['A', 'B', 'C']*3, 'val' : np.arange(1,10)})

最有效的方法是什么?

谢谢

杰克

推荐答案

选项1
不能100%确定效率,但是最简单的方法是使用 df.melt .

Option 1
Not 100% sure on efficiency, but the simplest way to do this is with df.melt.

df.rename_axis('row')\
  .reset_index()\
  .melt('row', value_name='val', var_name='col')\
  .sort_values(['row', 'col'])

  row col  val
0   A   A    1
3   A   B    2
6   A   C    3
1   B   A    4
4   B   B    5
7   B   C    6
2   C   A    7
5   C   B    8
8   C   C    9


选项2
stack -


Option 2
Another simple option with stack -

v = df.stack().reset_index()
v.columns=['row', 'col', 'val']
v

或者

df.stack().rename_axis(['row', 'col']).reset_index(name='val')

  row col  val
0   A   A    1
1   A   B    2
2   A   C    3
3   B   A    4
4   B   B    5
5   B   C    6
6   C   A    7
7   C   B    8
8   C   C    9

这篇关于高效扁平化 pandas 数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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