Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return rows with max/min values at bottom of dataframe (python/pandas)

I want to write a function that can look at a dataframe, find the max or min value in a specified column, then return the entire datafrane with the row(s) containing the max or min value at the bottom.

I have made it so that the rows with the max or min value alone get returned.

def findAggregate(df, transType, columnName=None):

    if transType == 'max1Column':
        return df[df[columnName] == df[columnName].max()]

    elif transType == 'min1Column':
        return df[df[columnName] == df[columnName].min()]

Given the dataframe below, I want to check col2 for the MIN value

Original Dataframe:

col1     col2     col3
blue     2        dog
orange   18       cat
black    6        fish

Expected output:

col1     col2     col3
blue     2        dog
orange   18       cat
black    6        fish
blue     2        dog

Actual output:

col1     col2     col3
blue     2        dog
like image 810
BeansMama Avatar asked Dec 06 '22 09:12

BeansMama


2 Answers

Focus on the index values

And use one loc

i = df.col2.idxmin()
df.loc[[*df.index] + [i]]

     col1  col2  col3
0    blue     2   dog
1  orange    18   cat
2   black     6  fish
0    blue     2   dog

Same idea but with Numpy and iloc

i = np.arange(len(df))
a = df.col2.to_numpy().argmin()
df.iloc[np.append(i, a)]

     col1  col2  col3
0    blue     2   dog
1  orange    18   cat
2   black     6  fish
0    blue     2   dog
like image 110
piRSquared Avatar answered May 11 '23 01:05

piRSquared


Use idxmin or idxmax:

edited to .loc after AndyL's comment

df.append(df.loc[df['col2'].idxmin()], ignore_index=True)

     col1  col2  col3
0    blue     2   dog
1  orange    18   cat
2   black     6  fish
3    blue     2   dog
like image 37
Erfan Avatar answered May 11 '23 00:05

Erfan