是否有可能计算2个或更多的列的最大/最小值,如果在另一列中的值等于在Python大熊猫的特定值?

问题描述 投票:2回答:1

我用进口大熊猫这个csv文件:

Date     Type   Price1  Price2  Price3  LowestBuy   HighestSell
01-02-19 BUY    0.1201  0.1202  0.1205      
01-02-19 SELL   0.1198  0.1199  0.1202      

现在我想最小的colums价格1,Price2,Price3添加到该行的LowestBuy列,如果类型(列2)等于买入。当类型为卖出我想最大的colums价格1,Price2,Price3的添加到HighestSell列。这可能吗?

这是我到目前为止的代码:

import pandas as pd

path = "orderbookData/NEOBTC2019-02-02.csv"

df = pd.read_csv(path, na_values=0)

for row in df:
    if(df["type"] == "BUY"):
        df["lowestBuy"] = df[["Price1", "Price2", "Price3"]].min(axis=1)
    if(df["type"] == "SELL"):
        df["highestSell"] = df[["Price1", "Price2", "Price3"]].max(axis=1)

print(df)

当我运行此代码我收到此错误信息:

Exception has occurred: ValueError
The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
  File "D:\test.py", line 10, in <module>
    if(df["type"] == "BUY"):
python-3.x pandas
1个回答
0
投票

使用DataFrame.loc

df.loc[df['Type'] == 'BUY', 'LowestBuy'] = df[['Price1','Price2','Price3']].min(1)
df.loc[df['Type'] == 'SELL', 'HighestSell'] = df[['Price1','Price2','Price3']].max(1)

    Date        Type    Price1  Price2  Price3  LowestBuy   HighestSell
0   01-02-19    BUY     0.1201  0.1202  0.1205  0.1201      NaN
1   01-02-19    SELL    0.1198  0.1199  0.1202  NaN         0.1202
© www.soinside.com 2019 - 2024. All rights reserved.