I have a DF like below
df = pd.DataFrame({'category' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
'size': [20, 0, 10, 30, 30, 0, 0, 10],
'price': [5, 0, 2, 10, 10, 0, 0, 3],
'flag' : [0,0,0,0,0,0,0,0]
})
I would like to change 0 in ['size'] column into the max value of the category so
df['size'] = np.where(df['size'].eq(0), df.groupby('category')['size'].transform('max'), df['size'])
df['price'] = np.where(df['price'].eq(0), df.groupby('category')['price'].transform('max'), df['price'])
And output would be like
df = pd.DataFrame({'category' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
'size': [20, 20, 10, 30, 30, 30, 10, 10],
'price': [5, 5, 2, 10, 10, 10, 3, 3],
'flag' : [0,0,0,0,0,0,0,0]
})
(process so far confirmed)
But now I would like to know which row has been changed so I assigned a ['flag'] column and would like to change the value 0 to 1 when any other value in the same row has been changed. So desired output would be like below
df = pd.DataFrame({'category' : ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C'],
'size': [20, 20, 10, 30, 30, 30, 10, 10],
'price': [5, 5, 2, 10, 10, 10, 3, 3],
'flag' : [0,1,0,0,0,1,1,0]
})
Is there anyway I can do this one line with the transform sentence? Or any other good way?