python - 根据特定条件过滤数据

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

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

<表类=“s-表”> <标题> 日期时间 音量 价格 <正文> 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. 通过日期时间列上的分组依据查找最大交易量的价格。
  2. 计算有多少个价格值低于 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

For Datetime = 2020-08-05 09:15:00, only one value is below 516 (504, ignoring rows with zero volume) for Datetime = 2020-08-05 09:20:00, two values are below 548 (476 & 526, ignoring rows with zero volume)

最佳答案

尝试使用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)

资源:

<表类=“s-表”> <标题> 日期时间 音量 价格 Count_below_prc <正文> 0 2020-08-05 09:15:00 1960 516 1 1 2020-08-05 09:20:00 1980 548 2

关于python - 根据特定条件过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66611522/

相关文章:

python - 为 Python 3 安装 ipdb?

python - 如何在 python 中读取大型 .jl 文件

python - 只能比较具有相同标签的Series对象错误与if语句 - Python

python - 如何将 std.error 写入文件,但将 std.out 写入 python 控制台?

python - 导入错误: No module named readability

Python:float 的子类可以在其构造函数中使用额外的参数吗?

python-3.x - Google 使用 selenium 搜索下一页

python - 按照 scrapy 中的重定向链接

python - 返回不正确的正数#

python - 将 0 或 1 的实例计数到系列中