Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rows corresponding to the minimum with pandas groupby

I have a table need to groupby by condition:

R_num ORG name level
13    Dm   Ad   17
13    Dm   Af   16

When i use it gives me 13 Dm Ad 16, which is like data being manipulated.

df1=df.reset_index().groupby(['R_num','ORG']).agg({'name':'first','level':['min']})

The result I want is 13 Dm Af 16, I know probably something wrong with 'name':'first' but how do i fix this please?

Thank you

like image 736
S.Gu Avatar asked Jan 12 '19 02:01

S.Gu


People also ask

How do you find the minimum value in pandas?

Pandas DataFrame min() MethodThe min() method returns a Series with the minimum value of each column. By specifying the column axis ( axis='columns' ), the max() method searches column-wise and returns the minimum value for each row.

How do I select a row in Groupby pandas?

You can group DataFrame rows into a list by using pandas. DataFrame. groupby() function on the column of interest, select the column you want as a list from group and then use Series. apply(list) to get the list for every group.

Is Iterrows faster than apply?

The results show that apply massively outperforms iterrows . As mentioned previously, this is because apply is optimized for looping through dataframe rows much quicker than iterrows does. While slower than apply , itertuples is quicker than iterrows , so if looping is required, try implementing itertuples instead.

How do you find the minimum value in a row?

Use min() function to find the minimum value over the index axis. 2) Get minimum values of every row : Use min() function on a dataframe with 'axis = 1' attribute to find the minimum value over the row axis.


1 Answers

IIUC, you should use groupby and idxmin:

# df.loc[df.groupby(['R_num','ORG'])['level'].agg('idxmin')]
df.loc[df.groupby(['R_num','ORG'])['level'].idxmin()]

   R_num ORG name  level
1     13  Dm   Af     16
like image 151
cs95 Avatar answered Sep 23 '22 03:09

cs95