【问题标题】:AttributeError: 'function' object has no attribute 'sum' pandasAttributeError:'function'对象没有属性'sum'pandas
【发布时间】:2018-04-26 13:36:14
【问题描述】:

我在 Pandas 中有以下数据框...

+-----------------------+
|              | count  |
+-----------------------+
| group        |        |
+-----------------------+
| 11-          | 99435  |
+-----------------------+
| Bachelor+    | 64900  |
+-----------------------+
| Just 12      | 162483 |
+-----------------------+
| Some College | 61782  |
+-----------------------+

我想执行以下代码,但出现错误...

death_2013['percent_of_total'] = death_2013.count.apply(
     lambda x: (x / death_2013.count.sum()))

我收到以下错误...

AttributeError: 'function' object has no attribute 'apply'

我检查了death_2013.dtypescount 是一个int64。我无法弄清楚代码有什么问题。

【问题讨论】:

  • count 是列名。我可以做death_2013.count.applydeath_2013['count'].apply,但它们似乎都不起作用。奇怪的是,我有这行代码处理不同的数据集。
  • 错误信息提示它是一个函数对象
  • 为什么不death_2013['count'].apply()
  • 天啊!!!似乎count 是 pandas 或 python 中的保留字。我更改了列名,现在 apply() 正在工作

标签: python python-3.x pandas dataframe


【解决方案1】:

有一个pandas.DataFrame.count 方法,它隐藏了您的列名。这就是您收到此错误消息的原因 - 正在访问绑定方法 count,这显然不起作用。

在这种情况下,您应该简单地使用['name_of_column'] 语法来访问两个位置的count 列,并且在将来命名列时要注意DataFrame 方法名称。

death_2013['percent_of_total'] = death_2013['count'].apply(
    lambda x: (x / death_2013['count'].sum()))

但请注意,在这种特殊情况下,无需使用 apply - 您可以简单地将整个系列除以平均值。

death_2013['count'] / death_2013['count'].sum()

【讨论】:

  • 我宁愿改变变量名。我在你的解决方案之前就弄清楚了。感谢您确认我的怀疑。
  • @Gilbert 不客气!这是使用该语法以及尝试设置新列的缺点之一。
【解决方案2】:

问题在于数据帧有一个count 方法。如果要在名为 count 的列上运行 apply(),请使用语法

death_2013['count'].apply()

或者,重命名列。

【讨论】:

    猜你喜欢
    • 2016-03-10
    • 2022-01-26
    • 2019-05-17
    • 2017-07-04
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多