bor*_*ice 13 python dataframe melt pandas
假设以下DataFrame:
key.0 key.1 key.2 topic
1 abc def ghi 8
2 xab xcd xef 9
Run Code Online (Sandbox Code Playgroud)
如何将所有key.*列的值组合到单个列'key'中,该列与对应于key.*列的主题值相关联?这是我想要的结果:
topic key
1 8 abc
2 8 def
3 8 ghi
4 9 xab
5 9 xcd
6 9 xef
Run Code Online (Sandbox Code Playgroud)
请注意,key.N列的数量在某些外部N上是可变的.
Ale*_*der 28
您可以融化数据框:
>>> 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
Run Code Online (Sandbox Code Playgroud)
它还为您提供密钥的来源.
From v0.20,melt是该类的第一类功能pd.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
Run Code Online (Sandbox Code Playgroud)
好的,因为当前答案之一被标记为与此问题的重复,我将在这里回答。
通过使用 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
Run Code Online (Sandbox Code Playgroud)
在尝试了各种方法之后,我发现以下内容或多或少是直观的,前提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)
Run Code Online (Sandbox Code Playgroud)
生成的数据框符合要求:
topic key
0 8 abc
1 8 def
2 8 ghi
3 9 xab
4 9 xcd
5 9 xef
Run Code Online (Sandbox Code Playgroud)
您可能需要打印中间结果以全面了解该过程。如果您不介意列数超出需要,那么关键步骤是set_index('topic'),stack()和reset_index(name='key')。