Home > Net >  Taking max of absolute values of two df columns in python
Taking max of absolute values of two df columns in python

Time:07-23

The questions looks very easy but I did not find a suitable intuitive answer. Suppose I have a df.

df = pd.DataFrame({"A": [-1,2,3], "B": [-2, 8, 1], "C": [-5, -6, 7]})

I want to create a column 'D' which gives the max of absolute values between 'A' and 'B'. In short what I am expecting is kind of the following form.

df["D"] = (df["A"].abs(), df["B"].abs()).max()

or df["D"] = max(df["A"].abs(), df["B"].abs())

or df["D"] = max(abs(df["A"]), abs(df["B"])

Obviously, none of them works because the syntax is taken from SAS and Excel. Help please.

CodePudding user response:

IIUC, You want this:

df['D'] = df[['A', 'B']].abs().max(axis=1)
print(df)

   A  B  C  D
0 -1 -2 -5  2
1  2  8 -6  8
2  3  1  7  3
  • Related