如何从单个列中获取多个列?

时间:2017-08-03 13:48:55

标签: python pandas

我有一个这样的专栏:

         Genre
Action|Crime|Drama|Thriller                 
Action|Crime|Thriller                          
Drama|Thriller                                 
Crime|Drama                                    
Horror|Thriller                                
Crime|Drama|Mystery|Thriller                   
Documentary                                    
Comedy|Crime                                   
Action|Adventure|Sci-Fi  
.....
so on.

我想要的是像多列一样输出:

it generate various column of genre eg:
action  scifi crime adventure . . . . .
0       1      0     1     0  
1       0      0     0     0

2 个答案:

答案 0 :(得分:3)

使用.str.splitstackget_dummies

df['Genre'].str.split('|',expand=True).stack().str.get_dummies().sum(level=0)

输出:

   Action  Adventure  Comedy  Crime  Documentary  Drama  Horror  Mystery  \
0       1          0       0      1            0      1       0        0   
1       1          0       0      1            0      0       0        0   
2       0          0       0      0            0      1       0        0   
3       0          0       0      1            0      1       0        0   
4       0          0       0      0            0      0       1        0   
5       0          0       0      1            0      1       0        1   
6       0          0       0      0            1      0       0        0   
7       0          0       1      1            0      0       0        0   
8       1          1       0      0            0      0       0        0   

   Sci-Fi  Thriller  
0       0         1  
1       0         1  
2       0         1  
3       0         0  
4       0         1  
5       0         1  
6       0         0  
7       0         0  
8       1         0  

答案 1 :(得分:1)

首先获取一列,然后在此列上执行.values[0] 其次使用先前生成的字符串,将其拆分为|列表。
使用df[df[list]]可以为您提供所需的响应。

结束(对于单个条目):

genres = list(df['Genre'].values[0].split('|'))
df[genres]