【问题标题】:Filter data with specific condition过滤特定条件的数据
【发布时间】:2021-03-13 08:33:06
【问题描述】:

我需要从下面给出的示例数据框中根据以下条件找到结果:

Datetime Volume Price
2020-08-05 09:15:00 1033 504
2020-08-05 09:15:00 1960 516
2020-08-05 09:15:00 0 450
2020-08-05 09:15:00 1724 520
2020-08-05 09:15:00 0 500
2020-08-05 09:15:00 1870 540
2020-08-05 09:20:00 1024 476
2020-08-05 09:20:00 1980 548
2020-08-05 09:20:00 0 480
2020-08-05 09:20:00 1426 526
2020-08-05 09:20:00 0 586
2020-08-05 09:20:00 1968 588
  1. 在日期时间列上使用 group-by 查找最大交易量的价格。
  2. 计算有多少价格值低于 Sl No 1 的价格(忽略交易量为零的行)

我想要我的结果数据框如下:

Datetime             Volume       Price  Count_below_prc
2020-08-05 09:15:00  1960         516    1
2020-08-05 09:20:00  1980         548    2

对于 Datetime = 2020-08-05 09:15:00,只有一个值低于 516 (504, Datetime = 2020-08-05 09:20:00 时忽略体积为零的行), 两个值低于 548(476 和 526,忽略体积为零的行)

【问题讨论】:

标签: python python-3.x pandas dataframe pandas-groupby


【解决方案1】:

尝试使用groupbyapply

def func(row):
    x = (row[row['Volume']==max(row['Volume'])])
    x['Count_below_prc']=(row.loc[row['Price'].lt(x['Price'].values[0]) & row['Volume'].ne(0), 'Price'].count())
    return x

res = df.groupby('Datetime',as_index=False).apply(func).reset_index(drop=True)

分辨率:

Datetime Volume Price Count_below_prc
0 2020-08-05 09:15:00 1960 516 1
1 2020-08-05 09:20:00 1980 548 2

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
  • 1970-01-01
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 2023-01-09
  • 2012-12-08
相关资源
最近更新 更多