gpt4 book ai didi

pandas - 在 Pandas 中获得最多三个计算

转载 作者:行者123 更新时间:2023-12-03 23:39:14 27 4
gpt4 key购买 nike

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

  • 我有一张我正在用 Pandas 阅读的工作表,其中有许多带有值的列。
  • 我需要运行三个计算,它们一次使用来自不同列的位。
  • 我需要在一位代码中返回这些计算的最大值,然后将其添加到新列中。

  • 我在使用 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.maximum reduce :

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

    关于pandas - 在 Pandas 中获得最多三个计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66963975/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com