How do you compute minimum from pandas data frame columns, without creating temporary column?

Viewed 47

Suppose, I have a pandas data frame df with columns A, B and C. I would like to compute the row-wise minimum from arithmetic operator on the columns, specifically df['D']=min(df['A']+dF['B']*3, df['C']*np.sqrt(12)). I have seen related questions, and it would seem like I would need to first create two columns for the arguments in the min function, and them perform min of axis =1. I was wondering if there was another way, without creating the temporary columns.

1 Answers

Without creating new columns, you can use apply:

df['D'] = df.apply(lambda x: min(x['A'] + x['B']*3, x['C']*np.sqrt(12), axis=1)

But it's best just do:

df['D'] = np.mininum(df['A']+dF['B']*3, df['C']*np.sqrt(12))

which creates two intermediate columns/series but is much faster thanks to vectorization.

Related