[英]Create Pandas column with the max of two calculated values from other columns
I want to create a column with the maximum value between 2 values calculated from other columns of the data frame.我想创建一个列,其最大值介于从数据框的其他列计算的 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().
The desired outcome is a new df column ['Max Col'] with the maximum value of the above calculations.期望的结果是具有上述计算最大值的新 df 列 ['Max Col']。
I know there is the long solution of creating two new columns with the calculations and then apply .max(axis=1) .我知道用计算创建两个新列然后应用.max(axis=1)的长期解决方案。 I am looking for a straight solution.
我正在寻找一个直接的解决方案。
Thanks.谢谢。
Use np.maximum
:使用
np.maximum
:
df['max'] =np.maximum(df['A']*3, df['B']+df['A'])
Output: Output:
A B max
0 1 -2 3
1 2 8 10
2 3 1 9
import pandas as pd
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
# map the max function to a zip of your calculations
df['max'] = list(map(max, zip(df['A']*3, df['B']+df['A'])))
print(df)
A B max
0 1 -2 3
1 2 8 10
2 3 1 9
You can use the apply
method -您可以使用
apply
方法 -
df['max'] = df.apply(lambda x: max(x['A']*3, x['A'] + x['B']), axis=1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.