Home > Enterprise >  Changing values in grouped dataframe based on first row value of the column in that group
Changing values in grouped dataframe based on first row value of the column in that group

Time:09-19

I am using the below code to arrange some data. It is grouped by 'ID' and 'L' and I have used a condition to print True in the MT column if it is True. What I want is that When the first row of the group is true, every other row in that group should print true irrespective of the condition (e.g in the output below,the fifth row in MT column should also show True, because the first row evaluated to true).

import pandas as pd
df=pd.DataFrame({'TS' : [20,25,30,35,45,50,55,58,65,75,60,62,72,77],"ID" : [22,22,23,23,23,23,23,23,23,23,24,24,24,24],"L" : [1,2,1,2,2,2,1,1,2,2,1,1,2,2]})
df2=(df.assign(TS=df['TS'].abs())
    .groupby(['ID','L'])['TS'].agg([('Min' , 'min'), ('Max', 'max')])
    .add_prefix('TS'))
df3=(df2.assign(WT=df2['TSMax']-df2['TSMin'])
    .assign(MT=df2['TSMax'].gt(df2.groupby('ID')['TSMin'].shift(-1))))
df3

Output:

enter image description here

CodePudding user response:

You can use groupby, index on the MT column, and then transform with a lambda that checks if the value is True.

df3['MT'] = df3.groupby('ID')['MT'].transform(lambda x: x.values[0] if x.values[0] else x)

Output:

enter image description here

  • Related