我有一个包含文本和子字符串的列。目标是通过文本迭代,如果有匹配,我想在新列中打印该匹配,而不是仅仅查找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
的地方。
使用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更快