How to find minimum for each unique value for every column grouped by ID in pandas data frame

纵饮孤独 提交于 2020-01-16 08:08:10

问题


I have a pandas dataframe and would like to find minimum value for each column grouped by ID.

#Input data 

df=pd.DataFrame({ 'id':[1,1,1,1,2,2,2,2],
                   'a':range(8), 'b':range(8,0,-1) })

#expected output is the minimum value for each id and column (a, b)
id  a    b  
1   0    5
2   4    1   


回答1:


df.groupby('id', as_index=False).agg(min) will do just that.

id  a  b
1   0  5
2   4  1



回答2:


You can use df.groupby('id').min()

Result:

    a  b
id      
1   0  5
2   4  1


来源:https://stackoverflow.com/questions/59217144/how-to-find-minimum-for-each-unique-value-for-every-column-grouped-by-id-in-pand

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!