以下代码必须执行以下几个步骤:
将差异乘以下表
我有以下代码
if df['Wholesale Data Usage'] >= df['mbs']:
if df['mbs'] == "32":
df['Additional Charge'] = (df['Wholesale Data Usage'] - df[
'mbs']) * 0.5
elif df['mbs'] == "64":
df['Additional Charge'] = (df['Wholesale Data Usage'] - df[
'mbs']) * 0.5
elif df['mbs'] == "128":
df['Additional Charge'] = (df['Wholesale Data Usage'] - df[
'mbs']) * 0.4
elif df['mbs'] == "256":
df['Additional Charge'] = (df['Wholesale Data Usage'] - df[
'mbs']) * 0.4
elif df['mbs'] == "512":
df['Additional Charge'] = (df['Wholesale Data Usage'] - df[
'mbs']) * 0.3
elif df['mbs'] == "1024":
df['Additional Charge'] = (df['Wholesale Data Usage'] - df[
'mbs']) * 0.3
else:
df['Additional Charge'] = 0
else:
df['Additional Charge'] = 0
不确定我做错了什么。
答案 0 :(得分:0)
首先,对于32,你乘以0.5而不是0.56。
然后,您似乎已经混淆了字符串和整数。如果df['Wholesale Data Usage']
和df['mbs']
中存储的数据是String类型,那么您不能检查大于(>=
),也不能从另一个中减去一个。
我怀疑字典中存储的数据类型为整数或 Float 或 Double 。在这种情况下,您尝试将数据与字符串进行比较,并应更改以下内容:
if df['mbs'] == "32":
为:
if df['mbs'] == 32:
并为每次比较做同样的事情
答案 1 :(得分:0)
你的代码很难读,难以调试。编码风格将帮助您看到我自己的错误。如果你这样写的怎么办?
mbs = df['mbs']
wdu = df['Wholesale Data Usage']
ac = 0
if wdu >= mbs and mbs == "32" : ac = (wdu - mbs) * 0.56
if wdu >= mbs and mbs == "64" : ac = (wdu - mbs) * 0.5
if wdu >= mbs and mbs == "128" : ac = (wdu - mbs) * 0.4
if wdu >= mbs and mbs == "256" : ac = (wdu - mbs) * 0.4
if wdu >= mbs and mbs == "512" : ac = (wdu - mbs) * 0.3
if wdu >= mbs and mbs == "1024" : ac = (wdu - mbs) * 0.3
df['Additional Charge'] = ac
据说你有类型问题。我比较的第一个等式mbs=="32"
就像你有一个字符串一样。然后在等式中,您尝试添加值,就好像它们包含一个int - 这不会起作用。让这些类型合理。
mbs = float(df['mbs'])
wdu = float(df['Wholesale Data Usage'])
ac = 0
if wdu >= mbs and mbs == 32 : ac = (wdu - mbs) * 0.56
if wdu >= mbs and mbs == 64 : ac = (wdu - mbs) * 0.5
if wdu >= mbs and mbs == 128 : ac = (wdu - mbs) * 0.4
if wdu >= mbs and mbs == 256 : ac = (wdu - mbs) * 0.4
if wdu >= mbs and mbs == 512 : ac = (wdu - mbs) * 0.3
if wdu >= mbs and mbs == 1024 : ac = (wdu - mbs) * 0.3
df['Additional Charge'] = str(ac) #<- you need to know what the expected type is here.
答案 2 :(得分:0)
我认为您的逻辑以及代码逐步完成逻辑的方式存在一些问题,例如:您检查mbs
列是否等于32,但如果Wholesale Data Usage
列与mbs
列之间的差异等于32,则确实如此。
这应该可以在不编辑太多代码的情况下修复逻辑:
df['mbs'] = np.where(df['Wholesale Data Usage'] >= df['mbs'], df['Wholesale Data Usage']-df['mbs'], 0)
if df['mbs'] == "32":
df['Additional Charge'] = (df['mbs']) * 0.5
elif df['mbs'] == "64":
df['Additional Charge'] = (df['mbs']) * 0.5
elif df['mbs'] == "128":
df['Additional Charge'] = (df['mbs']) * 0.4
elif df['mbs'] == "256":
df['Additional Charge'] = (df['mbs']) * 0.4
elif df['mbs'] == "512":
df['Additional Charge'] = (df['mbs']) * 0.3
elif df['mbs'] == "1024":
df['Additional Charge'] = (df['mbs']) * 0.3
else:
df['Additional Charge'] = 0