Pandas DataFrame将多列值堆叠到单列中 [英] Pandas DataFrame stack multiple column values into single column

查看:135
本文介绍了Pandas DataFrame将多列值堆叠到单列中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假定以下数据框:

  key.0 key.1 key.2  topic
1   abc   def   ghi      8
2   xab   xcd   xef      9

如何将所有key.*列的值组合到一个单独的列"key"中,该列与与key.*列对应的主题值相关联?这是我想要的结果:

How can I combine the values of all the key.* columns into a single column 'key', that's associated with the topic value corresponding to the key.* columns? This is the result I want:

   topic  key
1      8  abc
2      8  def
3      8  ghi
4      9  xab
5      9  xcd
6      9  xef

请注意,key.N列的数量在某些外部N上是可变的.

Note that the number of key.N columns is variable on some external N.

推荐答案

您可以融化数据框:

>>> keys = [c for c in df if c.startswith('key.')]
>>> pd.melt(df, id_vars='topic', value_vars=keys, value_name='key')

   topic variable  key
0      8    key.0  abc
1      9    key.0  xab
2      8    key.1  def
3      9    key.1  xcd
4      8    key.2  ghi
5      9    key.2  xef

它也为您提供了密钥的来源.

It also gives you the source of the key.

v0.20开始,meltpd.DataFrame类的第一类函数:

From v0.20, melt is a first class function of the pd.DataFrame class:

>>> df.melt('topic', value_name='key').drop('variable', 1)

   topic  key
0      8  abc
1      9  xab
2      8  def
3      9  xcd
4      8  ghi
5      9  xef

这篇关于Pandas DataFrame将多列值堆叠到单列中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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