data = {'Payment_type' =['Mastercard','Visa','Visa','Diners'],'Price' = [1200,600,300,5000]}
我正在努力如何根据付款类型修改价格。 这就是我的代码,这是错误的
for i in df['Payment_Type']:
if i == 'Visa':
df['Price']*0.01
elif i=='Matercard':
df['Price']*0.02
elif i == 'Diners':
df['Price']*0.03
else:
df['Price']*0.04
答案 0 :(得分:0)
您可以这样操作:
cards = ['Visa','Mastercard','Diners']
for card in cards:
if card == 'Visa':
df.loc[df['Payment_type']==card,'Price'] *= 0.01
elif card == 'Mastercard':
df.loc[df['Payment_type']==card,'Price'] *= 0.02
elif card == 'Diners':
df.loc[df['Payment_type']==card,'Price'] *= 0.03
else:
df.loc[~df['Payment_type'].isin(cards),'Price'] *= 0.04
这使用了else
循环的for
分支,实践中总是很有趣。
答案 1 :(得分:0)
让我们尝试使用dict
创建map
d = dict(zip(cards, [0.01,0.02,0.03]))
data.price = data.price*data.card.map(d).fillna(0.04)