Home > Software design >  how to change value based on criteria pandas
how to change value based on criteria pandas

Time:11-03

I have a following problem. I have this df:

d = {'id': [1, 1, 2, 2, 3], 'value': [0, 1, 0, 0, 1]}
df = pd.DataFrame(data=d)

I would like to have a new column where value will be 1 if in any other cases it is also 1. See desired output:

d = {'id': [1, 1, 2, 2, 3], 'value': [0, 1, 0, 0, 1], 'newvalue': [1, 1, 0, 0, 1]}
df = pd.DataFrame(data=d)

How can I do it please?

CodePudding user response:

If need set 0,1 by condition - here at least one 1 use GroupBy.transform with GroupBy.any for mask and casting to integers for True, False to 1,0 map:

df['newvalue'] = df['value'].eq(1).groupby(df['id']).transform('any').astype(int)

Alternative:

df['newvalue'] = df['id'].isin(df.loc[df['value'].eq(1), 'id']).astype(int)

Or if only 0,1 values is possible simplify solution for new column by maximal values per groups:

df['newvalue'] = df.groupby('id')['value'].transform('max')
print (df)
   id  value  newvalue
0   1      0         1
1   1      1         1
2   2      0         0
3   2      0         0
4   3      1         1

CodePudding user response:

either:

df.assign(newvalue=(df.id==1)|(df.value==1))

or:

import numpy as np
df['newvalue'] = np.where((df.id==1)|(df.value==1),1,0)
  • Related