Pandas pivot table 或 groupby 列的绝对最大值

Pandas pivot table or groupby absolute maximum of column

我有一个数据框 df 为:

Col1    Col2
A      -5
A       3
B      -2
B       15

我需要得到以下信息:

Col1    Col2
A      -5
B       15

通过从 Col2 中选择绝对最大值来为 Col1 中的每个组做出决定。我不确定如何进行此操作。

使用DataFrameGroupBy.idxmax with pass absolute values for indices and then select by DataFrame.loc:

df = df.loc[df['Col2'].abs().groupby(df['Col1']).idxmax()]
#alternative with reassign column
df = df.loc[df.assign(Col2 = df['Col2'].abs()).groupby('Col1')['Col2'].idxmax()]
print (df)
  Col1  Col2
0    A    -5
3    B    15