data = {'Payment_type' =['Mastercard','Visa','Visa','Diners'],'Price' = [1200,600,300,5000]}
I'm struggling with how can I modify the price based on the payment type. This is what I code and it is wrong
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
You can do it this way:
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
This uses the else
branch of the for
loop which is always fun to put into practise.
Let us try create dict
with map
d = dict(zip(cards, [0.01,0.02,0.03]))
data.price = data.price*data.card.map(d).fillna(0.04)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.