首页 > 解决方案 > 在给定字符串中查找数据框的列值的pythonic方法

问题描述

我有一个像这样的熊猫数据框:

data={
    'col1':['New Zealand', 'Gym', 'United States'],
    'col2':['Republic of South Africa', 'Park', 'United States of America'],
}
df=pd.DataFrame(data)
print(df)

            col1                      col2
0    New Zealand  Republic of South Africa
1            Gym                      Park
2  United States  United States of America

我有一个句子可能包含来自数据框任何列的单词。我想获取给定句子中存在的列中的值以及它们所在的列。我见过一些类似的解决方案,但它们与给出的句子与列值相匹配,而不是相反。目前,我正在这样做:

def find_match(df,sentence):
    "returns true/false depending on the matching value and column name where the value exists"
    arr=[]
    cols=[]
    flag=False
    for i,row in df.iterrows():
        if row['col1'].lower() in sentence.lower():
            arr.append(row['col1'])
            cols.append('col1')
            flag=True
        elif row['col2'].lower() in sentence.lower():
            arr.append(row['col2'])
            cols.append('col2')
            flag=True
    return flag,arr,cols

sentence="I live in the United States"
find_match(df,sentence)  # returns (True, ['United States'], ['col1'])

我想要一种更 Pythonic 的方式来做到这一点,因为它在相当大的数据帧上花费了大量时间,而且它对我来说似乎不是 Pythonic。

我不能使用 .isin() 因为它需要一个字符串列表并将列值与给定的整个句子匹配。我也尝试过执行以下操作,但它会引发错误:

df.loc[df['col1'].str.lower() in sentence]  # throws error that df['col1'] should be a string

任何帮助将不胜感激。谢谢!

标签: pythonpandasdataframe

解决方案


我会做这样的事情:

def find_match(df,sentence):
    ids = [(i,j) for j in df.columns for i,v in enumerate(df[j]) if v.lower() in sentence.lower()]
    return len(ids)>0, [df[id[1]][id[0]] for id in ids], [id[1] for id in ids]

这使:

find_match(df, sentence = 'I regularly go to the gym in the United States of America')

(True,
 ['Gym', 'United States', 'United States of America'],
 ['col1', 'col1', 'col2'])

从我的感觉来看,这很像 pythonic,尽管可能有更优雅的方式来更多地使用 pandas 函数。


推荐阅读