我有一个数据框,sega_df
:
>>> sega_df
0 1 2
Tails 20161016
Knuckles 20170202 20101216
Sonic 20160623 20101203 20160603
Amy 20160923
Shadow 20160919 20160723
Cream 20110309
Silver 20160405
Blaze 20161014
是否可以为一列以上的字符制作重复的行,并将其直接移到原始行名下? (Knuckles
,Sonic
和Shadow
)。
所需的输出
>>> sega_df
0
Tails 20161016
Knuckles 20170202
Knuckles 20101216
Sonic 20160623
Sonic 20101203
Sonic 20160603
Amy 20160923
Shadow 20160919
Shadow 20160723
Cream 20110309
Silver 20160405
Blaze 20161014
答案 0 :(得分:1)
这是将df.stack()
和df.droplevel()
与series.to_frame()
一起使用的一种方式
df.stack().droplevel(1).to_frame()
0
Tails 20161016.0
Knuckles 20170202.0
Knuckles 20101216.0
Sonic 20160623.0
Sonic 20101203.0
Sonic 20160603.0
Amy 20160923.0
Shadow 20160919.0
Shadow 20160723.0
Cream 20110309.0
Silver 20160405.0
Blaze 20161014.0
答案 1 :(得分:0)
这是使用熔化的另一种方式:
df = df.melt(id_vars='', value_name='0').dropna().drop('variable', axis=1)
返回:
0
Tails 20161016.0
Knuckles 20170202.0
Sonic 20160623.0
Amy 20160923.0
Shadow 20160919.0
Cream 20110309.0
Silver 20160405.0
Blaze 20161014.0
Knuckles 20101216.0
Sonic 20101203.0
Shadow 20160723.0
Sonic 20160603.0