Python 在多个布尔列中拆分dataframe列
我有一个包含10K行电影数据的csv 在“流派”列中,数据如下所示:Python 在多个布尔列中拆分dataframe列,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个包含10K行电影数据的csv 在“流派”列中,数据如下所示: Adventure|Science Fiction|Thriller Action|Adventure|Science Fiction|Fantasy Action|Crime|Thriller Western|Drama|Adventure|Thriller 我想根据类型栏创建多个子栏(即动作是/否、冒险是/否、戏剧是/否等) 问题1:如何首先确定“流派”列中所有独特的流派标题 问题2:在我确定了所有独特的体裁标题后,如何
Adventure|Science Fiction|Thriller
Action|Adventure|Science Fiction|Fantasy
Action|Crime|Thriller
Western|Drama|Adventure|Thriller
我想根据类型栏创建多个子栏(即动作是/否、冒险是/否、戏剧是/否等)
问题1:如何首先确定“流派”列中所有独特的流派标题
问题2:在我确定了所有独特的体裁标题后,如何创建所有必要的['insert-genre'yes/no]列?使用:
或:
要获得更好的性能,请使用:
详细信息:
print (df['col'].str.get_dummies('|'))
Action Adventure Crime Drama Fantasy Science Fiction Thriller \
0 0 1 0 0 0 1 1
1 1 1 0 0 1 1 0
2 1 0 1 0 0 0 1
3 0 1 0 1 0 0 1
Western
0 0
1 0
2 0
3 1
df = pd.concat([df] * 10000, ignore_index=True)
In [361]: %timeit pd.DataFrame(mlb.fit_transform(df['col'].str.split('|')) ,columns=mlb.classes_, index=df.index)
10 loops, best of 3: 120 ms per loop
In [362]: %timeit df['col'].str.get_dummies('|')
1 loop, best of 3: 324 ms per loop
In [363]: %timeit pd.get_dummies(df['col'].str.split('|').apply(pd.Series).stack()).sum(level=0)
1 loop, best of 3: 7.77 s per loop
计时:
print (df['col'].str.get_dummies('|'))
Action Adventure Crime Drama Fantasy Science Fiction Thriller \
0 0 1 0 0 0 1 1
1 1 1 0 0 1 1 0
2 1 0 1 0 0 0 1
3 0 1 0 1 0 0 1
Western
0 0
1 0
2 0
3 1
df = pd.concat([df] * 10000, ignore_index=True)
In [361]: %timeit pd.DataFrame(mlb.fit_transform(df['col'].str.split('|')) ,columns=mlb.classes_, index=df.index)
10 loops, best of 3: 120 ms per loop
In [362]: %timeit df['col'].str.get_dummies('|')
1 loop, best of 3: 324 ms per loop
In [363]: %timeit pd.get_dummies(df['col'].str.split('|').apply(pd.Series).stack()).sum(level=0)
1 loop, best of 3: 7.77 s per loop
假设您的列名为
Genres
,这是一种方法
res = pd.get_dummies(df['Genres'].str.split('|').apply(pd.Series).stack()).sum(level=0)
# Action Adventure Crime Drama Fantasy ScienceFiction Thriller Western
# 0 0 1 0 0 0 1 1 0
# 1 1 1 0 0 1 1 0 0
# 2 1 0 1 0 0 0 1 0
# 3 0 1 0 1 0 0 1 1
然后,您可以通过pd.DataFrame.applymap
将二进制值转换为“否”/“是”:
df = df.applymap({0: 'no', 1: 'yes'}.get)
非常感谢。这对我有帮助!
res = pd.get_dummies(df['Genres'].str.split('|').apply(pd.Series).stack()).sum(level=0)
# Action Adventure Crime Drama Fantasy ScienceFiction Thriller Western
# 0 0 1 0 0 0 1 1 0
# 1 1 1 0 0 1 1 0 0
# 2 1 0 1 0 0 0 1 0
# 3 0 1 0 1 0 0 1 1
df = df.applymap({0: 'no', 1: 'yes'}.get)