Python 如何从列表中查找datframe中的子字符串以创建新列?
我需要根据与列表匹配的子字符串创建一个新列 我有两个类似的列表:Python 如何从列表中查找datframe中的子字符串以创建新列?,python,pandas,numpy,Python,Pandas,Numpy,我需要根据与列表匹配的子字符串创建一个新列 我有两个类似的列表: 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 我有这样的数据帧: positive_list
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
我有这样的数据帧:
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?使用with,这里不是使用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
谢谢是否有可能忽略案例敏感性?当第一个字母是大写时,我无法察觉