【问题标题】:User defined function not working with Pandas用户定义的函数不适用于 Pandas
【发布时间】:2020-02-08 08:55:52
【问题描述】:

我正在学习 Python Pandas,所以写了一些代码来试验agg 使用的用户定义函数,如下所示。

import pandas as pd

def combine_cities(series):
       return reduce(lambda x, y: x + ', ' + y, series)

data = pd.DataFrame({'Country': ['Russia','USA','China','USA','China'],
                    'City':['Moscow','Boston','Wuhan','New York','Beijing']})
a = data.groupby('Country').agg(combine_cities)
print(a)

但是,我收到以下错误。知道我在这里做错了什么吗?

NameError                                 Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\groupby\ops.py in agg_series(self, obj, func)
    662         try:
--> 663             return self._aggregate_series_fast(obj, func)
    664         except Exception:

~\Anaconda3\lib\site-packages\pandas\core\groupby\ops.py in _aggregate_series_fast(self, obj, func)
    680         grouper = reduction.SeriesGrouper(obj, func, group_index, ngroups, dummy)
--> 681         result, counts = grouper.get_result()
    682         return result, counts

pandas\_libs\reduction.pyx in pandas._libs.reduction.SeriesGrouper.get_result()

pandas\_libs\reduction.pyx in pandas._libs.reduction.SeriesGrouper.get_result()

....

【问题讨论】:

  • 我试过了,它可以工作......(python 3.8,pandas 1.0.0,在 Spyder 中运行)
  • 奇怪。我在 Jupyter 笔记中运行了它,但它失败了。
  • 你用的是哪个版本的python?
  • 我正在使用 Python3。我现在意识到我必须添加 from functools import reduce,因为 reduce 已从 Python3 中删除,

标签: python python-3.x pandas aggregate user-defined-functions


【解决方案1】:

出现错误的原因是 Python3 删除了 reduce 函数。因此,我必须添加以下内容才能使其正常工作。

from functools import reduce

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-01
    • 1970-01-01
    相关资源
    最近更新 更多