基于分组和条件更新数据框列

Update Dataframe Column based on Grouping and Conditionals

我有三列代表我的数据。我正在尝试根据前两列的输入更新最后一列 'Val'。

我想要 'Range' 中的最大值,按 'Cat' 列分类。之后,我想根据该组中 'Val' 列的最小值更新 'Val' 列。

Input
    Cat Range Val
0    1    0   1.0
2    1    2   1.5
3    1    3   2.0
5    1    5   9.0
6    2    0   1.5
7    2    5   2.0
8    2   10   0.5
9    2   15   2.8
10   2   20   9.0 

Desired Output (Only Lines 5 and 10 change):
    Cat Range Val
0    1    0   1.0
2    1    2   1.5
3    1    3   2.0
5    1    5   1.0
6    2    0   1.5
7    2    5   2.0
8    2   10   0.5
9    2   15   2.8
10   2   20   0.5 

我的 pandas 基础知识建议使用这种方法,但它不起作用,我似乎无法解决它。

df.loc[df.groupby(['Cat'])['Range'].max(), 'Val'] = df.groupby('Cat')['Val'].min()

如果需要按 Val 列进行比较,您可以将 lambda 函数与 numpy.where 一起使用:

f = lambda x: np.where(x == x.max(), x.min(), x)
df['Val'] = df.groupby(['Cat'])['Val'].transform(f)
print (df)
    Cat  Range  Val
0     1      0  1.0
2     1      2  1.5
3     1      3  2.0
5     1      5  1.0
6     2      0  1.5
7     2      5  2.0
8     2     10  0.5
9     2     15  2.8
10    2     20  0.5

如果需要比较 Range 列中的 max 使用 GroupBy.transform 如果需要替换每组的所有最大值:

m = df['Range'].eq(df.groupby(['Cat'])['Range'].transform('max'))
df.loc[m, 'Val'] = df.groupby('Cat')['Val'].transform('min')

print (df)
    Cat  Range  Val
0     1      0  1.0
2     1      2  1.5
3     1      3  2.0
5     1      5  1.0
6     2      0  1.5
7     2      5  2.0
8     2     10  0.5
9     2     15  2.8
10    2     20  0.5

如果您只需要替换每组 Range 的第一个 max 值,您可以使用 df.loc and DataFrameGroupBy.idxmax :

In [3545]: (df.loc[df.groupby('Cat')['Range'].idxmax(), 'Val'] = 
            df.groupby('Cat')['Val'].transform('min'))

In [3546]: df
Out[3546]: 
    Cat  Range  Val
0     1      0  1.0
2     1      2  1.5
3     1      3  2.0
5     1      5  1.0
6     2      0  1.5
7     2      5  2.0
8     2     10  0.5
9     2     15  2.8
10    2     20  0.5
df.merge(df.groupby(['Cat'])['Range'].max().reset_index(), how='inner').groupby('Cat')['Val'].min()

这是您要找的吗?