Min and max row from pandas groupby

2020-08-01 02:30发布

I have a pandas dataframe which I grouped on column 'groupID'.

gb = df.groupby('groupID')

Each row is a has a x and y coordinate and a residual (distance from the line x=y). Now I want to find the gradient between 2 points(x,y) in a group where the residual is the biggest and the smallest. I know how to use gb['residual'].min() and max() but that does not give me the row.

How can I calculate this?

df[gb ['residual'].idxmin()]

标签: python pandas
1条回答
【Aperson】
2楼-- · 2020-08-01 03:30

I think you need find all indices from max and min value of column residual by DataFrameGroupBy.idxmax and DataFrameGroupBy.idxmin and then select by loc:

df1 = df.loc[df.groupby('groupID').residual.idxmax()]
df2 = df.loc[df.groupby('groupID').residual.idxmin()]
查看更多
登录 后发表回答