Using Pandas to Find Minimum Values of Grouped Rows

前端 未结 2 1699
感情败类
感情败类 2021-01-12 04:04

This might be a trivial question but I\'m still trying to figure out pandas/numpy.

So, suppose I have a table with the following structure:

group_id          


        
相关标签:
2条回答
  • 2021-01-12 04:22
    • focus on just ['col1', 'col2', 'col3']
    • see if they are equal to 1 with eq(1) equivalent to == 1
    • see if any are equal to one along axis=1 with any(1)
    • use loc to make assignment

    anyone = df[['col1', 'col2', 'col3']].eq(1).any(1)
    df.loc[anyone, 'A'] = np.nan
    

    numpy equivalent

    anyone = (df[['col1', 'col2', 'col3']].values == 1).any(1)
    df.A = np.where(anyone, np.nan, df.A)
    
    0 讨论(0)
  • 2021-01-12 04:41

    To get the minimum of column A for each group use transform

    df.groupby('group_id')['A'].transform('min')
    
    0 讨论(0)
提交回复
热议问题