Reputation: 2533
I have the following Pandas dataframe:
df = pd.DataFrame({'food' : ['spam', 'ham', 'eggs', 'pizza'],
'price' : [10, 8, 5, 17]
})
I'd like to be able to print the value of the food
column, but only if the corresponding value of the price
is greater than 7. I tried to use the following (yes, I know for loops are bad!):
if df['price'] > 7:
print(df['food'])
But, I get back the following error:
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
If I had to use a for loop, what would be the way to do so?
Thanks!
Upvotes: 0
Views: 5108
Reputation: 7923
You want something like this ?
df.loc[df['price']>7,:]
output:
food price
0 spam 10
1 ham 8
3 pizza 17
Update:
If you only want to show the 'food' column, then you just need to replace the :
in the loc
statement with the name of the column. (:
just means all columns of the dataframe)
df.loc[df['price']>=7, 'food']
Upvotes: 2
Reputation: 2533
I solved it this way:
for idx, elem in enumerate(df['price']):
if elem > 7:
print(df['food'][idx])
Upvotes: 0