【问题标题】:ValueError - DataFunctionValueError - 数据函数
【发布时间】:2021-12-14 16:51:40
【问题描述】:

运行代码时出现此错误:

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

代码:

def calculate_pay(vehicle,hours):
    if vehicle == 'Bike':
        pay = 9.99
    elif vehicle == 'Walking & Public Transportation':
        pay = 9.99
    else:
        pay = 14.00
    return hours*pay

这里是excel数据的例子:

我想打印输出:

ID - Printed per row of data 

Vehicle Type used

Hours 

Total Pay calculated from the function 

这将被导出回 Excel。

【问题讨论】:

  • 请说明vehicle的定义以及您如何称呼calculate_pay...
  • 导出回excel是什么意思?另外请分享完整的代码,而不仅仅是功能。您需要打印函数中不存在的其他详细信息。我们会更容易理解。示例输出也会有所帮助。
  • 你需要使用df['Vehicle', 'Hours'].apply(calculate_pay)
  • @user17242583 车辆将引用数据表中的 excel 列。我用这个来调用calculate_pay: df["Total Pay"] = df.apply(calculate_pay(df["Vehicle"], df["Hours"])) 我不确定这是否正确,因为我是新的所以请耐心等待,对不起。
  • 你有这个想法,你只是在使用 Pandas 有点错误。我会写一个答案来帮助你。

标签: python pandas valueerror


【解决方案1】:

试试这个:

prices = {
    'Bike': 9.99,
    'Walking & Public Transportation': 9.99,
}
default_price = 14.00

df['TotalPay'] = df.apply(lambda x: prices[x.get('Vehicle', default_price)]*x['Hours'], axis=1)

【讨论】:

  • 我可以将其添加到价格列表中,而不是默认价格 = 14.00? 14.00 是货运自行车的价格。这将如何改变最后一行代码?感谢您的帮助
  • 如果Vehicle 列中的行未在prices 字典中列出,则使用default_price。就像'Cargo-bike': 14.00, 或电子表格中出现的任何内容,到字典。
  • 运行代码时出现 KeyError: 'Cargo-bike'
  • 不应该的。您是否将 'Cargo-bike': 14.00, 添加到 prices 字典中?
  • 我现在已将货运自行车添加到列表中。我是否仍然需要在代码中保留 default_price 或者我现在可以删除 Cargo-bike to price 吗?代码现在似乎运行良好。有什么办法可以打印出来,显示每一行,包括身份证、车辆、小时数和总工资?
猜你喜欢
  • 2021-10-04
  • 2022-10-22
  • 2018-12-07
  • 1970-01-01
  • 1970-01-01
  • 2023-01-02
  • 2020-09-26
  • 2020-09-18
  • 1970-01-01
相关资源
最近更新 更多