通过独特的价值融合几列

时间:2016-09-08 12:14:19

标签: python excel pandas

我有一个包含很多列的数据集。数据的结构如下:

id  Artist 1    Artist 2    Artist 3
1   Red hot     
2   Wiz         Red hot 
3   Red hot     Wiz        Bronson 
4   Bronson     Bruce      Red hot
5   Wiz         Bronson 
6   Red Hot     

我需要它像这样:

id  Artist
1   Red hot     
2   Wiz     
2   Red hot     
3   Red hot     
3   Wiz     
3   Bronson     
4   Red hot
4   Bronson     
4   bruce       
5   Wiz     
5   Bronson     
6   Red hot     

在熊猫中有一种简单的方法吗?我尝试过使用此反应中的融合,但它并不是我的目标: pandas convert some columns into rows

提前thx!

1 个答案:

答案 0 :(得分:0)

我认为你可以使用:

#if column `id` is not index, first set it to index
df.set_index('id', inplace=True)
#create multiindex from columns
df.columns = df.columns.str.split(expand=True)
print (df)
     Artist                  
          1        2        3
id                           
1   Red hot      NaN      NaN
2       Wiz  Red hot      NaN
3   Red hot      Wiz  Bronson
4   Bronson    Bruce  Red hot
5       Wiz  Bronson      NaN
6   Red Hot      NaN      NaN

#reshape it
print (df.stack().reset_index(drop=True, level=1).reset_index())
    id   Artist
0    1  Red hot
1    2      Wiz
2    2  Red hot
3    3  Red hot
4    3      Wiz
5    3  Bronson
6    4  Bronson
7    4    Bruce
8    4  Red hot
9    5      Wiz
10   5  Bronson
11   6  Red Hot