【问题标题】:python pandas | triple conditional statments大熊猫 |三重条件语句
【发布时间】:2021-12-30 20:32:26
【问题描述】:
volume price datetime
100 3 2021-09-29 04:00:00-04:00
900 2 2021-09-29 04:30:00-04:00
900 5 2021-09-29 05:30:00-04:00
500 9 2021-09-29 06:00:00-04:00
900 22 2021-09-29 06:30:00-04:00
900 1 2021-09-29 07:00:00-04:00

我正在尝试做的事情:“在 2021-09-29 04:15:00-04:00 和 2021-09-29 06:35:00-04:00 之间,以最大交易量返回价格。如果有超过一个最大数量的行/记录,则返回其中的最低价格(预期输出为 2)"

我有以下内容,但我不知道如何在其中嵌套 between 语句

df[df.volume == df.volume.max()].price.min()

【问题讨论】:

    标签: python pandas datetime conditional-statements


    【解决方案1】:

    您可以使用df.sort_values 方法对多列进行排序。这是一个例子:

    import pandas as pd
    
    df = pd.DataFrame(
        {
            "volume": [100, 900, 900, 500, 900, 900],
            "price": [3, 2, 5, 9, 22, 1],
            "datetime": pd.to_datetime(
                [
                    "2021-09-29 04:00:00-04:00",
                    "2021-09-29 04:30:00-04:00",
                    "2021-09-29 05:30:00-04:00",
                    "2021-09-29 06:00:00-04:00",
                    "2021-09-29 06:30:00-04:00",
                    "2021-09-29 07:00:00-04:00",
                ]
            ),
        }
    )
    # select the date range
    df_in_date = df.loc[
        (df["datetime"] >= "2021-09-29 04:15:00-04:00")
        & (df["datetime"] <= "2021-09-29 06:35:00-04:00")
    ]
    # sort by the volume (descending) then the price (ascending)
    # the first row contains the lowest price for the maximum volume
    lowest_price = df_in_date.sort_values(
        ["volume", "price"], ascending=(False, True), ignore_index=True
    ).loc[0, "price"]
    print(lowest_price)
    

    【讨论】:

      猜你喜欢
      • 2021-12-30
      • 2020-07-25
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2022-12-11
      • 2020-09-22
      • 2018-06-27
      • 2021-08-27
      相关资源
      最近更新 更多