Pandas DataFrame将多个列值堆叠为单个列

时间:2015-12-19 22:30:33

标签: python pandas dataframe melt

假设以下DataFrame:

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

如何将所有关键。*列的值合并到一个列'键中,与关键字。*列对应的主题值相关联?这是我想要的结果:

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

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

3 个答案:

答案 0 :(得分:27)

您可以融化数据框:

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

它还为您提供了密钥的来源。

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

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

答案 1 :(得分:4)

好的,因为当前答案中的一个标记为重复此问题,我将在这里回答。

使用wide_to_long

pd.wide_to_long(df, ['key'], 'topic', 'age').reset_index().drop('age',1)
Out[123]: 
   topic  key
0      8  abc
1      9  xab
2      8  def
3      9  xcd
4      8  ghi
5      9  xef

答案 2 :(得分:3)

在尝试了各种方法之后,我发现以下内容或多或少都是直观的,前提是stack魔法被理解为:

# keep topic as index, stack other columns 'against' it
stacked = df.set_index('topic').stack()
# set the name of the new series created
df = stacked.reset_index(name='key')
# drop the 'source' level (key.*)
df.drop('level_1', axis=1, inplace=True)

生成的数据框符合要求:

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

您可能希望打印中间结果以完整了解该过程。如果您不介意拥有比所需更多的列,则关键步骤为set_index('topic')stack()reset_index(name='key')

相关问题