Pandas str.contains-在字符串中搜索多个值并在新列中打印这些值

3 python string pandas

我刚刚开始使用Python进行编码,并希望构建一个解决方案,在该解决方案中,您将搜索字符串以查看其是否包含一组给定的值。

我在R中找到了一个类似的解决方案,该解决方案使用Stringr库:在字符串中搜索值,如果该值存在,则将其全部打印在新列中

以下代码似乎有效,但我也想输出我要查找的三个值,而此解决方案将仅输出一个值:

#Inserting new column
df.insert(5, "New_Column", np.nan)

#Searching old column
df['New_Column'] = np.where(df['Column_with_text'].str.contains('value1|value2|value3', case=False, na=False), 'value', 'NaN')
Run Code Online (Sandbox Code Playgroud)

------编辑------

所以我意识到我没有给出很好的解释,对此感到抱歉。

下面是一个示例,其中我匹配字符串中的水果名称,并且取决于它是否在字符串中找到任何匹配项,它将在新列中打印true或false。这是我的问题:我不想打印出true或false而是打印出它在字符串中找到的名称。苹果,橘子等

import pandas as pd
import numpy as np

text = [('I want to buy some apples.', 0),
         ('Oranges are good for the health.', 0),
         ('John is eating some grapes.', 0),
         ('This line does not contain any fruit names.', 0),
         ('I bought 2 blueberries yesterday.', 0)]
labels = ['Text','Random Column']

df = pd.DataFrame.from_records(text, columns=labels)

df.insert(2, "MatchedValues", np.nan)

foods =['apples', 'oranges', 'grapes', 'blueberries']

pattern = '|'.join(foods)

df['MatchedValues'] = df['Text'].str.contains(pattern, case=False)

print(df)
Run Code Online (Sandbox Code Playgroud)

结果

                                          Text  Random Column  MatchedValues
0                   I want to buy some apples.              0           True
1             Oranges are good for the health.              0           True
2                  John is eating some grapes.              0           True
3  This line does not contain any fruit names.              0          False
4            I bought 2 blueberries yesterday.              0           True
Run Code Online (Sandbox Code Playgroud)

想要的结果

                                          Text  Random Column  MatchedValues
0                   I want to buy some apples.              0           apples
1             Oranges are good for the health.              0           oranges
2                  John is eating some grapes.              0           grapes
3  This line does not contain any fruit names.              0          NaN
4            I bought 2 blueberries yesterday.              0           blueberries
Run Code Online (Sandbox Code Playgroud)

jpp*_*jpp 10

这是一种方法:

foods =['apples', 'oranges', 'grapes', 'blueberries']

def matcher(x):
    for i in foods:
        if i.lower() in x.lower():
            return i
    else:
        return np.nan

df['Match'] = df['Text'].apply(matcher)

#                                           Text        Match
# 0                   I want to buy some apples.       apples
# 1             Oranges are good for the health.      oranges
# 2                  John is eating some grapes.       grapes
# 3  This line does not contain any fruit names.          NaN
# 4            I bought 2 blueberries yesterday.  blueberries
Run Code Online (Sandbox Code Playgroud)


adr*_*adr 5

您需要设置regex标志(以将搜索解释为正则表达式):

whatIwant = df['Column_with_text'].str.contains('value1|value2|value3',
                                                 case=False, regex=True)

df['New_Column'] = np.where(whatIwant, df['Column_with_text'])
Run Code Online (Sandbox Code Playgroud)

------编辑------

根据更新的问题陈述,这是更新的答案:

您需要使用括号在正则表达式中定义一个捕获组,并使用该extract()函数返回在捕获组中找到的值。该lower()函数处理任何大写字母

df['MatchedValues'] = df['Text'].str.lower().str.extract( '('+pattern+')', expand=False)        
Run Code Online (Sandbox Code Playgroud)