redeemefy
redeemefy

Reputation: 4849

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

I have the following data frame in 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.dtypes and count is a int64. I can't figure out what is wrong with the code.

Upvotes: 4

Views: 23025

Answers (2)

miradulo
miradulo

Reputation: 29690

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

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

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.

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

Upvotes: 3

John Coleman
John Coleman

Reputation: 51998

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

death_2013['count'].apply()

Alternatively, rename the column.

Upvotes: 1

Related Questions