[英]How to input maximum value of two equations into pandas dataframe column?
I am trying to input into new column of dataframe maximum result of two equations based on different columns.我正在尝试输入 dataframe 基于不同列的两个方程的最大结果的新列。 Unfortunately I am having below error.不幸的是我有以下错误。 How should I change the code to make it work (I would like to stay with pandas library in this case)?我应该如何更改代码以使其工作(在这种情况下,我想继续使用 pandas 库)?
Prc1 Prc1 | Prc2 Prc2 | Price价格 |
---|---|---|
1.5 1.5 | 2.5 2.5 |
df['Price'] = max(((df['Prc1'] - df['Prc2']) / df['Prc1']).abs(), ((df['Prc1'] - df['Prc2']) / ['Prc2']).abs())
ValueError: The truth value of a Series is ambiguous. ValueError:Series 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all()使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()
Use numpy.maximum
:使用numpy.maximum
:
s = df['Prc1'] - df['Prc2']
df['Price'] = np.maximum((s / df['Prc1']).abs(), (s / df['Prc2']).abs())
Another idea with divide from right side by DataFrame.rdiv
: DataFrame.rdiv
从右侧划分的另一个想法:
df['Price'] = df[['Prc1','Prc2']].rdiv(df['Prc1'].sub(df['Prc2']), axis=0).abs().max(axis=1)
df = pd.DataFrame({'Prc1':[1,2,5], 'Prc2':[-5,8,-20]})
s = df['Prc1'] - df['Prc2']
df['Price1'] = np.maximum((s / df['Prc1']).abs(), (s / df['Prc2']).abs())
df['Price2'] = df[['Prc1','Prc2']].rdiv(df['Prc1'].sub(df['Prc2']),axis=0).abs().max(axis=1)
print (df)
Prc1 Prc2 Price1 Price2
0 1 -5 6.0 6.0
1 2 8 3.0 3.0
2 5 -20 5.0 5.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.