Pandas数据帧将多个列值堆栈到单个列中

2024-06-16 10:31:32 发布

您现在位置:Python中文网/ 问答频道 /正文

假设以下数据帧:

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

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

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

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


Tags: 数据key主题topicdefabc数目ghi
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')

好的,因为现在的答案之一是标记为这个问题的副本,我将在这里回答。

使用^{}

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

您可以熔化数据帧:

>>> 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.20meltpd.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

相关问题 更多 >