Nelson Gomes - 1 year ago 49

Python Question

I have a CSV file with two columns:

`fruits values`

bananas 2

apples 5

oranges 4

pineapples 2

I would like to sum the

`values`

`fruits`

I tried this:

`sum= 0`

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

sum=sum+folha['values'].sum()

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
Out[10]:
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
```