根据行长在Pandas DataFrame中创建新行

时间:2019-11-14 15:31:04

标签: python pandas

我有一个数据框,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

是否可以为一列以上的字符制作重复的行,并将其直接移到原始行名下? (KnucklesSonicShadow)。

所需的输出

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

2 个答案:

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