【发布时间】:2021-09-01 05:49:43
【问题描述】:
我有一个数据框df 并在对其应用函数时给出值错误。
df = pd.DataFrame({
'ID': range(1, 4),
'col1': [10, 5, 10],
'col2': [15, 10, 15],
'col3': [10, 15, 15],
'total': [35, 30, 40]
})
print(df)
ID col1 col2 col3 total
0 1 10 15 10 35
1 2 5 10 15 30
2 3 10 15 15 40
def round_up(value):
remainder = value % 5
if remainder == 0:
new_val = value
if remainder == 1:
new_val = value - 1
if remainder == 2:
new_val = value - 2
if remainder == 3:
new_val = value + 2
if remainder == 4:
new_val = value + 1
return new_val
df.iloc[:, 1:-1] = df.iloc[:, 1:-1].apply(round_up)
ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
【问题讨论】:
-
尝试使用applymap 而不是
apply。目前,您正在尝试将这些操作应用于整个列,这意味着remainder = value % 5会生成Series的值(在建议的副本中进行了更多解释)。applymap会将函数应用到每个 cell。