【问题标题】:pandas: exact match does not work in an if AND conditionpandas:完全匹配在 if AND 条件下不起作用
【发布时间】:2021-11-16 14:15:41
【问题描述】:

我有两个数据框如下:

data = {'First':  [['First', 'value'],['second','value'],['third','value','is'],['fourth','value','is']],
'Second': ['noun','not noun','noun', 'not noun']}

df = pd.DataFrame (data, columns = ['First','Second'])

data2 = {'example':  ['First value is important', 'second value is important too','it us good to know',
                  'Firstap is also good', 'aplsecond is very good']}

df2 = pd.DataFrame (data2, columns = ['example'])

并且我编写了以下代码,如果在 df 中与句子的第一个单词匹配,则从 df2 中过滤掉句子,前提是在第二列中我们与单词“名词”匹配。所以基本上有两个条件。

def checker():
    result =[]
    for l in df2.example:
        df['first_unlist'] = [','.join(map(str, l)) for l in df.First]
        if df.first_unlist.str.match(pat=l.split(' ', 1)[0]).any() and df.Second.str.match('noun').any():
            result.append(l)
    return result

但是,我意识到当我运行该函数时,我得到 ['First value is important', 'second value is important too'] 作为输出,这表明仅“名词”过滤器的第二个条件不起作用.所以我想要的输出是['第一个值很重要']。 我也尝试过 .str.contains() 和 .eq() 但我仍然得到相同的输出

【问题讨论】:

    标签: python pandas string match exact-match


    【解决方案1】:

    我建议在尝试匹配之前过滤掉df

    def checker():
        result = []
        for l in df2.example:
            first_unlist = [x[0] for x in df.loc[df.Second == 'noun', 'First']
            if l.split(' ')[0] in first_unlist:
                result.append(l)
        return result
    
    checker()
    ['First value is important']
    
    

    【讨论】:

    • 改进的解决方案供loc选择
    猜你喜欢
    • 1970-01-01
    • 2022-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-04
    • 2022-11-12
    相关资源
    最近更新 更多