Filtering data in Pandas returns error 'method' object is not iterable

Viewed 2747

I have a dataset as follows: I am going to filter rows where the counts value equals 1.

index      count
1           4
2           5
3           1
4           1

This is my code:

booleans =[]

for number in df1.count:
    if number ==1:
        booleans.append (True)
    else:
        booleans.append (False)

but it has this error:

'method' object is not iterable

I also tried this:

df[df.count==1]

but I had the following error:

KeyError: False

any suggestion?

3 Answers

Count is also a method of pandas DataFrame.

When you do df.count, pandas understands you are calling the count() method, not fetching your column that happens to have the same name. Doing df["count"] would solve your issue.

In your code the problem is with the this part df1.count. Actually, pandas is having a method count() which is used to count the no. of non-NA/null observations across the given axis.

And in your code it returns something like this,

<bound method DataFrame.count of   index count
0     1     4
1     2     5
2     3     1
3     4     1>

Instead of it, you can use df[df['count']=='1'] to get what you were looking for.

import pandas as pd

data = {"index":['1','2','3','4'],
        "count":['4','5','1','1']}

df = pd.DataFrame(data)
indexes = df[df['count']=='1']
print(indexes)

Output

     index count
   2     3     1
   3     4     1

The standard way to do this is to do the following:

Solution 1

df1[df1["count"]=='1']

Solution 2 However, if you really do want to get a list of booleans you might want to use lambdas:

booleans = list(df1['count'].apply(lambda x:x=='1').values)

You can then use this list to get the result you want like so:

df1[booleans]

This is basically the same thing as solution 1.

Related