Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative for multiple if statements using dataframe Pandas

Tags:

python

pandas

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
like image 882
g123456k Avatar asked Dec 07 '25 04:12

g123456k


2 Answers

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)
like image 172
jezrael Avatar answered Dec 08 '25 17:12

jezrael


Use isin:

df.loc[df['A'].isin((1, 2, 3, 5, 9)), 'A10'] = df['A'] +  df['B'] + 100 
like image 32
U12-Forward Avatar answered Dec 08 '25 16:12

U12-Forward