【发布时间】:2020-03-05 06:59:57
【问题描述】:
我想知道如何在 Pandas 中将 for 循环转换为 .apply() 方法。 我正在尝试遍历数据帧 (df1) 的一列并从第二个数据帧 (df2) 的子集中返回匹配项。我有一个函数来进行匹配(Matching),还有一个函数可以从 df2(Filter)中选择正确的子集。我想知道是否可以使用 Pandas 的 .apply() 方法来调用这两个函数。
我已经想出了如何将其作为一个 for 循环来执行(见下文),而且我似乎可以通过首先创建一个完整的函数来通过列表理解来做到这一点(见 here)但我有麻烦通过 Pandas .apply() 方法和 lambda 表达式来实现。
## Here is my Filter, which selects titles from df2 for one year
## either side of a target year
def Filter (year):
years = [year-1, year, year+1]
return df2[df2.year.isin(years)].title
# Here is my matching routine, it uses the process method from
# fuzzywuzzy
def Matcher(title, choices):
title_match, percent_match, match3 = process.extractOne(title,
choices, scorer=fuzz.token_sort_ratio)
return title_match
# Here is my solution using a for-loop
for index, row in df1.iterrows():
targets = Filter(row.year)
df1.loc[index,'return_match'] = Matcher(row.title, targets)
# Here's my attempt with a lambda function
df1['new_col'] = df1.title.apply(lambda x: Matcher(x,
Filter(df1.year)))
当我使用 lambda 函数时,似乎发生的情况是 Filter 函数仅在 .apply() 方法的第一次迭代中被调用,因此每个标题都与第一个过滤集匹配。有办法解决吗?
【问题讨论】:
标签: python pandas for-loop lambda