What is for alternative for multiple if statements using dataframe? Usually I use a simple approach as in example below, however, if more statements are necessary, not great.
In this particular example I am creating one column A10, based on A value. Probably this could be done in other, much shorter way:
df.loc[df['A'] == 1, 'A10'] = df['A'] + df['B'] + 100
df.loc[df['A'] == 2, 'A10'] = df['A'] + df['B'] + 200
df.loc[df['A'] == 3, 'A10'] = df['A'] + df['B'] + 300
df.loc[df['A'] == 5, 'A10'] = df['A'] + df['B'] + 400
df.loc[df['A'] == 9, 'A10'] = df['A'] + df['B'] + 500
You can use mapping by dictionary only for filtered rows:
d = {1:100,2:200,3:300,5:400,9:500}
m = df['A'].isin(d)
df.loc[m, 'A10'] = df['A'] + df['B'] + df.loc[m, 'A'].map(d)
For mapping all values in column, should be slowier if many not matched values:
d = {1:100,2:200,3:300,5:400,9:500}
m = df['A'].isin(d)
df.loc[m, 'A10'] = df['A'] + df['B'] + df['A'].map(d)
Use isin:
df.loc[df['A'].isin((1, 2, 3, 5, 9)), 'A10'] = df['A'] + df['B'] + 100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With