在 pandas 中获取三个计算的最大值

Getting the max of three calculations in pandas

我试图寻找答案,但找不到。如果有人有 link,那就更好了。我的问题如下。

  1. 我有一个 sheet 我正在阅读 pandas,其中有许多列,其中包含值。
  2. 我需要 运行 三个计算,它们一次使用来自不同列的位。
  3. 我需要 return 在一位代码中计算这些计算的最大值,然后将其添加到新列中。

我的数字 2 有问题。

这是我的代码的样子。

df = read_csv('file.csv')

df['Get New'] = maximum(df[Long] - df[Short], df[Long] + df[Short], df[Long] / df[Short])

df.to_csv('newFile.csv', index=False)

我知道最大值在这种情况下不起作用,但我似乎找不到什么可以。任何帮助表示赞赏。谢谢!

编辑:这是解决方法。

df['Get New'] = np.maximum(df['Long'] - df['Short'],  df['Long'] + df['Short'])
df['Get New'] = np.maximum(df['Get New'], df['Long'] / df['Short'])

np.maximumreduce 一起使用:

import numpy as np


df = pd.DataFrame({
         'Long':[7,8,9,4,2,3],
         'Short':[1,3,5,7,1,7],
})

df['Get New'] = np.maximum.reduce([df['Long'] - df['Short'], 
                                   df['Long'] + df['Short'], 
                                   df['Long'] / df['Short']])
print (df)
   Long  Short  Get New
0     7      1      8.0
1     8      3     11.0
2     9      5     14.0
3     4      7     11.0
4     2      1      3.0
5     3      7     10.0

备选方案是仅对成对使用 np.maximum

df['Get New'] = np.maximum(df['Long'] - df['Short'],  df['Long'] + df['Short'])
df['Get New'] = np.maximum(df['Get New'], df['Long'] / df['Short'])