[英]python panda: find a specific string in a column and fill the column matching the string
我有一个包含几列的数据框。 其中之一充满了由 | 分隔的电影“流派”,我将此列拆分为其他几列,以获得 X 列,每个列都填充了拆分值。 但是,我需要为每个“流派”设置 1 列,填充 1 或 0,具体取决于列的标题是在名义流派列中还是在拆分列之一中找到。 我的数据框设置如下:
df = pd.DataFrame({'A': ['drama|Action', 'Drama', 'Action'], 'A_split1': ['Drama', 'Drama', 'Action'],'A_split2': ['Action', 'None', 'None'],'Drama': [0, 0, 0], 'Action': [0, 0, 0], 'Western': [0, 0, 0]},
index = ['a1', 'a2', 'a3'])
df
但是我没有找到如何检查标题名称是否在字符串中以添加 1 或 0。
我认为你需要pop
的提取塔与str.get_dummies
并join
到原文:
df = pd.DataFrame({'A': ['Drama|Action', 'Drama', 'Action'], 'B':range(3)},
index = ['a1', 'a2', 'a3'])
print (df)
A B
a1 Drama|Action 0
a2 Drama 1
a3 Action 2
df = df.join(df.pop('A').str.get_dummies())
print (df)
B Action Drama
a1 0 1 1
a2 1 0 1
a3 2 1 0
如果想要原始列:
df = df.join(df['A'].str.get_dummies())
print (df)
A B Action Drama
a1 Drama|Action 0 1 1
a2 Drama 1 0 1
a3 Action 2 1 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.