Nelson Gomes Nelson Gomes - 1 year ago 77
Python Question

Count if another column contains a value

I have a CSV file with two columns:

fruits values
bananas 2
apples 5
oranges 4
pineapples 2

I would like to sum the
has "apples" in it. It should return 5 + 2 = 7.

I tried this:

sum= 0
if folha['fruits'].str.contains("apples"):

But it returns an error:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

Any thoughts?

Answer Source

This is pretty straightforward:

In [10]: df
       fruits  values
0     bananas       2
1      apples       5
2     oranges       4
3  pineapples       2

In [11]: df[df.fruits.str.contains('apples')]['values'].sum()
Out[11]: 7
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download