Computing the minimum value for each row in a Pandas DataFrame [duplicate]
Asked Answered
C

1

6

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()
Consequently answered 2/6, 2019 at 20:25 Comment(0)
E
9

Use pandas.DataFrame.min with axis=1:

df['Dmin'] = df.min(axis=1)
Extortion answered 2/6, 2019 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.