我需要根据与列表匹配的子字符串创建一个新列。
我有2个这样的列表:
positive_list = ['good', 'high', 'nice', 'fair']
negative_list = ['bad', 'worst', 'low']
我有这样的数据框:
id text
1 #bad_boy_here
2 #nice_but_low
3 high jump
4 what is good
我需要创建两个额外的负和正列
id text positive negative
1 #bad_boy_here NaN Neg
2 #nice_but_low Pos Neg
3 high jump Pos NaN
4 what is good Pos NaN
我正在考虑使用np.where
但未获得所需的输出,并且不确定如何在np.where中使用列表?
DataFrame.assign
与一起使用Series.str.contains
,此处不使用,np.nan
但None
为避免NaN
转换为字符串'nan'
:
df = df.assign(positive = np.where(df['text'].str.contains('|'.join(positive_list), case=False), 'Pos', None),
negative = np.where(df['text'].str.contains('|'.join(negative_list), case=False), 'Neg', None))
print (df)
id text positive negative
0 1 #bad_boy_here None Neg
1 2 #nice_but_low Pos Neg
2 3 high jump Pos None
3 4 what is good Pos None
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句