AttributeError: 'function' 对象没有属性 'sum' pandas

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42602399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:07:13  来源:igfitidea点击:

AttributeError: 'function' object has no attribute 'sum' pandas

pythonpython-3.xpandasdataframe

提问by Gilbert

I have the following data frame in Pandas...

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

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

I want to perform the following code but I'm getting an error...

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

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

I'm getting the following error...

我收到以下错误...

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

I checked the death_2013.dtypesand countis a int64. I can't figure out what is wrong with the code.

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

采纳答案by miradulo

There is a pandas.DataFrame.countmethod, which is shadowing the name of your column. This is why you're getting this error message - the bound method countis being accessed, which then obviously doesn't work.

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

In this case, you should simply use the ['name_of_column']syntax to access the countcolumn in both places, and be mindful of DataFrame method names when naming columns in the future.

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

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

Note however that in this particular case there is no need to use apply- you can simply divide the entire Series by the mean.

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

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

回答by John Coleman

The problem is that dataframes have a countmethod. If you want to run apply()on a columns named countuse the syntax

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

death_2013['count'].apply()

Alternatively, rename the column.

或者,重命名列。