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

时间:2018-02-05 21:27:20

标签: python string pandas

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

我在R中找到了一个使用字符串库的类似解决方案:Search for a value in a string and if the value exists, print it all by itself in a new column

以下代码似乎有效,但我也希望输出我正在寻找的三个值,此解决方案只输出一个值:

#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')

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

所以我意识到我没有给出那么好的解释,抱歉。

下面是一个示例,其中我匹配字符串中的水果名称,并且根据它是否在字符串中找到任何匹配项,它将在新列中打印出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)

结果

                                          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

通缉结果

                                          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

2 个答案:

答案 0 :(得分:4)

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

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

df['New_Column'] = np.where(whatIwant, df['Column_with_text'])

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

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

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

df['MatchedValues'] = df['Text'].str.lower().str.extract( '('+pattern+')', expand=False)        

答案 1 :(得分:1)

这是一种方式:

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