2017-08-03 53 views
1

我有这样一栏:如何从单个列中获取多个列?

  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 

回答

3

使用.str.splitstack,并get_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

首先要获取一列,然后在此列做.values[0]
其次使用先前生成的字符串,通过|列入清单。
使用df[df[list]]应该给你你想要的回应。

总括(用于单个条目):

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