Pandas DataFrame 将多列值堆叠到单列中
- 2025-04-10 09:44:00
- admin 原创
- 24
问题描述:
假设以下 DataFrame:
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 上是可变的。
解决方案 1:
您可以融化您的数据框:
>>> 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
,melt
是该类的一等函数pd.DataFrame
:
>>> df.melt('topic', value_name='key').drop('variable', axis=1)
topic key
0 8 abc
1 9 xab
2 8 def
3 9 xcd
4 8 ghi
5 9 xef
解决方案 2:
尝试了各种方法后,我发现以下内容或多或少是直观的,只要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')
。
解决方案 3:
好的,因为当前其中一个答案被标记为与该问题重复,所以我将在这里回答。
通过使用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
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD