【问题标题】:How can you call a second function while using a lambda function in an .apply() call in Python?在 Python 的 .apply() 调用中使用 lambda 函数时,如何调用第二个函数?
【发布时间】: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


    【解决方案1】:

    欢迎来到 SO JP。 我在这一行看到了一个问题:

    # Here's my attempt with a lambda function
    df1['new_col'] = df1.title.apply(lambda x: Matcher(x, Filter(df1.year)))
    

    您在所有 DataFrame 列 year 上调用 Filter,而作为您的 for 循环解决方案,您只想在该行的年份调用它。所以我建议在这样的行上使用 apply:

    df1['new_col'] = df1.apply(lambda row: Matcher(row.title, Filter(row.year)), axis=1)
    

    我希望这会有所帮助。

    【讨论】:

    • 这非常有帮助,我使用了它,它完全有效。很抱歉忘记感谢您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多