【问题标题】:Getting the max of three calculations in pandas在熊猫中获得三个计算的最大值
【发布时间】:2021-04-06 06:54:30
【问题描述】:

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

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

我遇到了数字 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'])

【问题讨论】:

    标签: pandas dataframe max calculation


    【解决方案1】:

    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'])
    

    【讨论】:

    • 我已调整为使用 np.maximum,但我收到此错误“RecursionError:超出最大递归深度”。我也在这些计算中使用 np.absolute,所以我不确定这是否会导致其他问题。
    • @IanLang - 列 LangShort 是数字吗?什么返回print (df.dtypes)
    • 他们以 float64 的形式返回
    • @IanLang - 你是对的,答案已被编辑。
    • 行得通!谢谢!我已经编辑了上面的原始帖子以考虑到这一点。
    猜你喜欢
    • 2018-06-01
    • 2021-02-24
    • 2021-09-30
    • 2012-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    相关资源
    最近更新 更多