Search code examples
python-3.xpandasmaxminobject-slicing

Min or Max of pandas data series between two rows


I have a pandas dataframe. Suppose the column names are 'A', 'B', and 'C'.

How can I calculate the min and/or max of data in column 'A' inclusive of only rows m to p? Where m < p and m != 0 and p < the number of rows in the dataframe.

What if I store the column names in a list and want to iterate over them in a loop and get the max.

colNames = ['A', 'B', 'C']
for col in colNames:
     # get the max here

Solution

  • By using .iloc and loc, assuming your m=1 and p=3

    colNames=['A','B']
    df.iloc[1:3,:].loc[:,colNames]
    Out[767]: 
       A  B
    1  2  2
    2  3  1
    df.iloc[1:3,:].loc[:,colNames].min() #get the min of each column
    Out[768]: 
    A    2
    B    1
    dtype: int64
    df.iloc[1:3,:].loc[:,colNames].min(1) # get the min of each row
    Out[769]: 
    1    2
    2    1
    dtype: int64
    

    Data input

    df = pd.DataFrame({"A": [1,2,3],
                       'B':[3,2,1],'C':[2,1,3]})