熊猫:打印“匹配项”而不是仅打印布尔结果

时间:2018-09-10 21:56:39

标签: string pandas dataframe

我有一列带有文本和子字符串的列。目标是遍历文本,如果有匹配项,我想在新列中打印该匹配项,而不是仅查找True / False语句。如何做到这一点?当前代码:

sLength = len(dfEx5)
substring = ['AmericanAir', 'JetBlue', 'SouthwestAir', 'united','USAirways', 'VirginAmerica']
dfEx5['mentions'] = pd.Series(1, index=dfEx5.index) #Add a new column 'mentions' with 1's
pd.options.mode.chained_assignment = None #To deal with the 'SettingWithCopyWarning'

dfEx5['mentions'] = next((substring for substring in dfEx5['text'] if substring in dfEx5['text']), True)

dfEx5['text']pandas.core.series.Series的地方。

1 个答案:

答案 0 :(得分:0)

使用apply方法来传递自定义函数:

substring = ['AmericanAir', 'JetBlue', 'SouthwestAir', 'united','USAirways', 'VirginAmerica']
df= pd.DataFrame([["AmericaAir5","JetBlue2"],["JetBlue2","SouthwestAir"]],columns=['text','what'])
def searchr(x,s):
    for i in s:
        if x.find(i)+1:
            return i
        else:
            continue
df["mentions"]=df['text'].apply(searchr,args=(substring,))

或者,您可以使用正则表达式:

import re
r = re.compile('('+"|".join(substring)+')')
df["m"] = df.text.str.extract(r)

第一种方法似乎比regex str concat快