Home > Mobile >  IF statement returning the index value. But getting the error The truth value of a series is ambiguo
IF statement returning the index value. But getting the error The truth value of a series is ambiguo

Time:04-21

I am trying to form a print statement based on a Value in a data frame. Where the desired outcome is a statement such as;

'the days upon which there is a value is Jan3, Jan4'

an example of my df is as follows;

Value
Jan2 0.0
Jan3 0.5
Jan4 0.5

what I tried was;

DaysWithValue = [] #an empty list
if df['Value'] > 0:
   DaysWithValue.append(df['Value'].index]

print('the days with value are;'   ' '   DaysWithValue)

the issue being I get an error message of;

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

None of the a.___() worked, I want it to operate for each row not for an overall truth.

even if the IF statement had worked i'm unsure if the print statement would work with the list as its not string.

any advice on a simpler way to achieve this?

CodePudding user response:

import pandas as pd

df = pd.DataFrame({"date": ['Jan 2', 'Jan 3', 'Jan 4'], "value": [0, 0.5, 0.4]})
dates_with_values = df[df['value'] > 0]['date'].tolist()
print(f"The dates with values: {', '.join(dates_with_values)}.")

Output:

The dates with values: Jan 3, Jan 4.

  • Related