【问题标题】:Pandas error: ValueError: The truth value of a Series is ambiguous. on applying a function to a dataframePandas 错误:ValueError:Series 的真值不明确。关于将函数应用于数据框
【发布时间】: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()。

【问题讨论】:

标签: python pandas


【解决方案1】:

当您跨多个列应用时,您需要使用applymap 而不是apply。此外,您的舍入函数也可以简化,见下文

df = pd.DataFrame({
    'ID': range(1, 4),
    'col1': [10, 5, 10],
    'col2': [15, 10, 15],
    'col3': [10, 15, 15],
    'total': [35, 30, 40]
})

def round_up(value):
    return (value + 2) // 5 * 5)

df.iloc[:, 1:-1] = df.iloc[:, 1:-1].applymap(round_up)

【讨论】:

    猜你喜欢
    • 2018-07-05
    • 2019-10-29
    • 2021-08-14
    • 2022-10-05
    • 2021-09-10
    • 2020-08-03
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多