gpt4 book ai didi

python - Python 和 Pandas 的问题 : Adding calculated column to dataframe that includes data from a function provides error

转载 作者:行者123 更新时间:2023-12-01 06:24:48 25 4
gpt4 key购买 nike

我正在尝试将计算列:“NetEarnings”添加到我的 DataFram“Wages”中。 “净利润”栏从年收入中减去税款;税是从我创建的用于计算税的函数中提取的。由于错误,它不会让我添加这个新列:

"TypeError: unsupported operand type(s) for -: 'float' and 'tuple'"

我已经尝试了几乎所有的方法,不确定我是否在某个地方犯了一个愚蠢的错误。感谢您的帮助!

代码:

def Tax(AnnualIncome):
if (0 < AnnualIncome) & (AnnualIncome <= 21450):
return (.15 * AnnualIncome)
elif (21450 < AnnualIncome) & (AnnualIncome <= 51900):
return (3215.5 + ((AnnualIncome - 21450) * .28))
else:
return (11,743.5 + ((AnnualIncome - 51900) * .31))

wages['Tax'] = wages['AnnualIncome'].apply(Tax)

# Problem line
wages['NetEarning'] = wages['AnnualIncome'] - wages['Tax']

enter image description here

错误:

TypeError: unsupported operand type(s) for -: 'float' and 'tuple'

最佳答案

除了 Ente 答案之外,

我建议使用 np.where 而不是 apply。 apply 比 for 循环快,但比 apply 慢得多。

一个可能的解决方案是:

np.where(df['AnnualIncome'] <= 21450, (.15 *df['AnnualIncome']), 
np.where(df['AnnualIncome'] <= 51900,
(3215.5 + ((df['income']- 21450) * .28)),
(11743.5 + (df['AnnualIncome'] - 51900) * .31)
)
)

关于python - Python 和 Pandas 的问题 : Adding calculated column to dataframe that includes data from a function provides error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60218204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com