IF 语句返回索引值。但是得到错误 The truth value of a series is ambiguous
IF statement returning the index value. But getting the error The truth value of a series is ambiguous
我正在尝试根据数据框中的值形成打印语句。期望的结果是这样的陈述;
'the days upon which there is a value is Jan3, Jan4'
我的df示例如下;
Value
Jan2
0.0
Jan3
0.5
Jan4
0.5
我试过的是;
DaysWithValue = [] #an empty list
if df['Value'] > 0:
DaysWithValue.append(df['Value'].index]
print('the days with value are;' + ' ' + DaysWithValue)
问题是我收到一条错误消息;
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
None 的 a.___() 起作用了,我希望它对每一行都起作用,而不是为了整体真相。
即使 IF 语句有效,我也不确定打印语句是否适用于列表,因为它不是字符串。
关于实现此目标的更简单方法有什么建议吗?
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)}.")
输出:
The dates with values: Jan 3, Jan 4.
我正在尝试根据数据框中的值形成打印语句。期望的结果是这样的陈述;
'the days upon which there is a value is Jan3, Jan4'
我的df示例如下;
Value | |
---|---|
Jan2 | 0.0 |
Jan3 | 0.5 |
Jan4 | 0.5 |
我试过的是;
DaysWithValue = [] #an empty list
if df['Value'] > 0:
DaysWithValue.append(df['Value'].index]
print('the days with value are;' + ' ' + DaysWithValue)
问题是我收到一条错误消息;
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
None 的 a.___() 起作用了,我希望它对每一行都起作用,而不是为了整体真相。
即使 IF 语句有效,我也不确定打印语句是否适用于列表,因为它不是字符串。
关于实现此目标的更简单方法有什么建议吗?
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)}.")
输出:
The dates with values: Jan 3, Jan 4.