如何从列表中查找datframe中的子字符串以创建新列?

2024-04-25 11:32:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要根据与列表匹配的子字符串创建一个新列

我有两个类似的列表:

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中使用列表


1条回答
网友
1楼 · 发布于 2024-04-25 11:32:46

^{}^{}一起使用,这里不是使用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

相关问题 更多 >