Take the maximum in absolute value from different columns and filter out NaN Python

gis20 picture gis20 · Dec 7, 2015 · Viewed 9.4k times · Source

This was my try. For example

df = pd.DataFrame({'a':[5,0,1,np.nan], 'b':[np.nan,1,4,3], 'c':[-3,-2,0,0]})
df.dropna(axis=1).max(axis=1,key=abs)

Filters out well the NaN values but it gets 0 or negative values instead of the highes in absolute value

The result should be one column with

5
-2
4
3

Answer

gis20 picture gis20 · Dec 7, 2015

I solved by

maxCol=lambda x: max(x.min(), x.max(), key=abs)
df.apply(maxCol,axis=1)