Printing the max and min values with pandas Python

Viewed 537

I am trying to write a function that prints out all the max and min values and their indexes for the specified columns in the input.csv file. The columns I want to return the max values of are referenced in the max_columns variable and the one to return min values are in the min_columns variable. However it doesn't go through the whole array values as intended I tried to do it with pandas howver it does not work. The code down below was achieved from my previous post:

input.csv file:

element,LNPT,SNPT,NLP,NSP,TNT,TPnL,MxPnL,MnPnL,MxU,MxD
[ 2.  2. 30.],0,0,4,4,8,-0.1,-0.0,-0.1,17127,-3
[ 2.  2. 40.],0,0,2,2,4,0.0,-0.0,-0.0,17141,-3
[ 2.  2. 50.],0,0,2,2,4,0.0,-0.0,-0.0,17139,-3
[ 2.  2. 60.],2,0,6,6,12,0.5,2.3,-1.9,17015,-3
[ 2.  2. 70.],1,0,4,4,8,0.3,0.3,-0.0,17011,-3

Code:

df = pd.read_csv('STDOutputs_Q1.csv')
max_columns= np.array([1,2,3,7,8,10])
min_columns = np.array([4,5,6,9])

def max_vals():
    max_index = df[max_columns].idxmax()
    max_values = df[max_columns].max()
    return results, index
    
def min_vals():
    min_index = df[min_columns].idxmin()
    min_values = df[min_columns].min()
    return results, index

max_values, max_index= max_vals()
min_values, min_index= min_vals()
1 Answers

max_columns and min_columns hold integer indexes, so you should iloc them as df.iloc[:, max_columns] and df.iloc[:, min_columns]:

max_columns = np.array([1, 2, 3, 7, 8, 10]) # numeric indexes
min_columns = np.array([4, 5, 6, 9])

def max_vals():
    max_index = df.iloc[:, max_columns].idxmax() # so not df[max_columns]
    max_values = df.iloc[:, max_columns].max()
    return max_values, max_index

def min_vals():
    min_index = df.iloc[:, min_columns].idxmin()
    min_values = df.iloc[:, min_columns].min()
    return min_values, min_index

Alternatively you could define max_columns and min_columns by name, in which case df[max_columns] and df[min_columns] would work:

max_columns = ['LNPT', 'SNPT', 'NLP', 'MxPnL', 'MnPnL', 'MxD'] # named indexes
min_columns = ['NSP', 'TNT', 'TPnL', 'MxU']

def max_vals():
    max_index = df[max_columns].idxmax() # so not df.iloc[:, max_columns]
    max_values = df[max_columns].max()
    return max_values, max_index

def min_vals():
    min_index = df[min_columns].idxmin()
    min_values = df[min_columns].min()
    return min_values, min_index
Related