简体   繁体   English

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

[英]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.

相关问题 创建熊猫中其他列的总和的计算所得列 - Create calculated column of sum values of other columns in pandas 根据其他两列的值,在 pandas 中创建一个新列 - Create a new column in pandas depending on values from two other columns Pandas:使用从预先存在的列计算的值在数据框中创建两个新列 - Pandas: create two new columns in a dataframe with values calculated from a pre-existing column 创建 Pandas 列,显示来自其他两列的最大重复对数 - Create Pandas column displaying the max number of repeated pairs from two other columns 熊猫根据其他两个具有日期时间值的列创建一个布尔列 - pandas create a boolean column based on two other columns with datetime values Pandas Dataframe 使用 Groupby 从其他两列的唯一值创建下一个未来日期的列 - Pandas Dataframe Create Column of Next Future Date from Unique values of two other columns, with Groupby pandas,根据其他两列的值创建一个新的唯一标识符列 - pandas, create a new unique identifier column based on values from two other columns 根据来自其他两列的条件文本值在 Pandas 中创建一个新列 - Create a new column in pandas based on conditional text values from two other columns 使用Pandas DataFrame中其他两列的键和值创建字典列 - Create column of dictionaries with keys and values from other two columns in Pandas DataFrame 根据Pandas中其他两个列的相等性从列中提取值 - Extract values from a column based on the equality of two other columns in Pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM