Search code examples
pythonpandasdataframesliceminimum

Computing the minimum value for each row in a Pandas DataFrame


I have this DataFrame df:

A   B   C   D
1   3   2   1
3   4   1   2
4   6   3   2
5   4   5   6

I would like to add a column that calculates the minimum values, by slicing columns A to D (the actual df is larger, so I need to slice it) ie

Dmin
1
1
2
4

I can calculate the min for 1 row as follows

df.iloc[0].loc['A':'D'].min()

I tried the following for the whole DataFrame, all of which gave NaN

df['Dmin']=df.loc[:,'A':'D'].min()

df['Dmin']=df.iloc[:].loc['A':'D'].min()

df['Dmin']=df.loc['A':'D'].min()

Solution

  • Use pandas.DataFrame.min with axis=1:

    df['Dmin'] = df.min(axis=1)