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
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With