I am trying to find a minimum number using groupby()
by comparing two columns (Each containing a time duration)
Sample data:
JavaScript
x
7
1
Ambulance_ID Centroid_ID Hospital_ID Regular_Ambu_TT MSU_TT
2
37 1 6 1,871884861 0,459994444
3
39 2 13 1,599971112 0,372125
4
6 3 6 1,307165278 0,080163889
5
42 4 12 1,411554445 0,285008333
6
37 5 14 1,968138334 0,424172222
7
Sample code: (It works for 1 column only)
JavaScript
1
3
1
Test_TT = pd.DataFrame()
2
Test_TT = df_A2C_TT_temp.loc[df_A2C_TT_temp.groupby('Centroid_ID').Regular_Ambu_TT.idxmin()]
3
I want to group my data by groupby('Centroid_ID')
by comparing Regular_Ambu_TT
and MSU_TT
to get a minimum value.
Advertisement
Answer
Here is one approach
- Get the min per column
- Get a min per row to get the final minimum .
JavaScript
1
6
1
df_mins = pd.DataFrame()
2
df_mins[['Centroid_ID', 'min_Regular_Ambu_TT']] = df_A2C_TT_temp.groupby('Centroid_ID')['Regular_Ambu_TT'].min().reset_index()
3
df_mins[['Centroid_ID', 'min_MSU_TT']] = df_A2C_TT_temp.groupby('Centroid_ID')['MSU_TT'].min().reset_index()
4
df_mins['min_per_group'] = df_mins[['min_Regular_Ambu_TT','min_MSU_TT']].min(axis=1)
5
df_mins
6