Pandas - 检查字符串列是否包含一对字符串

时间:2017-04-16 21:58:59

标签: python string pandas boolean-expression

假设我有一个像这样的DataFrame:

df = pd.DataFrame({'consumption':['squirrel eats apple', 'monkey eats apple', 
                                  'monkey eats banana', 'badger eats banana'], 
                   'food':['apple', 'apple', 'banana', 'banana'], 
                   'creature':['squirrel', 'badger', 'monkey', 'elephant']})

    consumption creature    food
0   squirrel eats apple squirrel    apple
1   monkey eats apple   badger  apple
2   monkey eats banana  monkey  banana
3   badger eats banana  elephant    banana

我想找到“生物”和“生物”的行。 “食物”组合出现在“消费”栏中,即如果苹果和松鼠一起出现,那么真实,但如果苹果与大象一起出现则是假的。同样,如果猴子&香蕉一起出现,然后是真的,但是Monkey-Apple会是假的。

我尝试的方法类似于:

creature_list = list(df['creature'])
creature_list = '|'.join(map(str, creature_list))

food_list = list(df['food'])
food_list = '|'.join(map(str, food_list))

np.where((df['consumption'].str.contains('('+creature_list+')', case = False)) 
          & (df['consumption'].str.contains('('+food_list+')', case = False)), 1, 0)

但这不起作用,因为我在所有情况下都是真的。

如何检查字符串对?

3 个答案:

答案 0 :(得分:4)

以下是一种可能的方式:

def match_consumption(r):
    if (r['creature'] in r['consumption']) and (r['food'] in r['consumption']):
        return True
    else:
        return False

df['match'] = df.apply(match_consumption, axis=1)
df

           consumption  creature    food  match
0  squirrel eats apple  squirrel   apple   True
1    monkey eats apple    badger   apple  False
2   monkey eats banana    monkey  banana   True
3   badger eats banana  elephant  banana  False

答案 1 :(得分:1)

检查字符串相等性是否过于简单?您可以测试字符串<creature> eats <food>是否等于consumption列中的相应值:

(df.consumption == df.creature + " eats " + df.food)

答案 2 :(得分:0)

我确定有更好的方法可以做到这一点。但这是一种方式。

import pandas as pd
import re

df = pd.DataFrame({'consumption':['squirrel eats apple', 'monkey eats apple', 'monkey eats banana', 'badger eats banana'], 'food':['apple', 'apple', 'banana', 'banana'], 'creature':['squirrel', 'badger', 'monkey', 'elephant']})

test = []
for i in range(len(df.consumption)):
    test.append(bool(re.search(df.creature[i],df.consumption[i])) & bool((re.search(df.food[i], df.consumption[i]))))
df['test'] = test