使用其他列中两个计算值的最大值创建 Pandas 列

Ale*_*xSB 8 python max dataframe pandas

我想创建一个列,其中的最大值介于从数据框的其他列计算得出的 2 个值之间。

import pandas as pd
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})

df['Max Col'] = max(df['A']*3, df['B']+df['A'])


ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Run Code Online (Sandbox Code Playgroud)

期望的结果是一个新的 df 列 ['Max Col'],其中包含上述计算的最大值。

我知道有一个很长的解决方案,即通过计算创建两个新列,然后应用.max(axis=1)。我正在寻找一个直接的解决方案。

谢谢。

Qua*_*ang 10

使用np.maximum

df['max'] =np.maximum(df['A']*3, df['B']+df['A'])
Run Code Online (Sandbox Code Playgroud)

输出:

   A  B  max
0  1 -2    3
1  2  8   10
2  3  1    9
Run Code Online (Sandbox Code Playgroud)