属性错误:'function'对象没有属性'sum' pandas

4

I have the following data frame in 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.dtypes,发现count是一个int64类型。我无法确定代码存在什么问题。


count 是列名。我可以使用 death_2013.count.apply 或者 death_2013['count'].apply,但是它们似乎都不起作用。奇怪的是,我在不同的数据集上使用这行代码时是有效的。 - redeemefy
错误信息表明它是一个函数对象。 - John Coleman
为什么不使用death_2013 ['count'] .apply()呢? - John Coleman
哦我的天啊!似乎count是pandas或Python中的保留字。我更改了列名,现在apply()可以正常工作了。 - redeemefy
2个回答

3

有一个名为pandas.DataFrame.count的方法,这个方法与你的列名同名。这就是为什么你会收到这个错误信息——正在访问绑定方法count,这显然行不通。

在这种情况下,在两个地方都使用['name_of_column']语法来访问count列,并在以后命名列时注意DataFrame方法的名称。

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

需要注意的是,在这种情况下,没有必要使用apply函数 - 您可以直接将整个序列除以平均值。

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

我宁愿更改变量名。我在你的解决方案之前就已经想到了。谢谢你确认了我的猜测。 - redeemefy
@Gilbert 不用谢!使用那种语法的缺点之一是尝试设置新列。 - miradulo

1
问题在于数据帧有一个 "count" 方法。如果您想在名为 "count" 的列上运行 "apply()",请使用以下语法。
death_2013['count'].apply()

或者,重命名该列。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接