【问题标题】:How to compress a data frame within a range?如何压缩范围内的数据帧?
【发布时间】:2014-10-18 22:06:18
【问题描述】:

对于每一美分,我想将体积加在一起。

所以在这个数据集中,价格在 188.415-188.42 之间的所有交易将它们的交易量相加,所有 188.43 的交易相加,等等。我目前正在使用 pandas 来管理数据,我不确定是什么我可以用它来完成这个功能。

示例数据:

Time|Volume|Price
09:30:00|200|188.42
09:30:00|500|188.41
09:30:00|100|188.415
09:30:00|100|188.41
09:30:00|590|188.42
09:30:00|100|188.415
09:30:00|100|188.4
09:30:00|200|188.42
09:30:00|900|188.41
09:30:00|249|188.42
09:30:00|100|188.41
09:30:00|300|188.415
09:30:00|300|188.42
09:30:00|100|188.43
09:30:00|100|188.44
09:30:00|900|188.43
09:30:00|200|188.42
09:30:00|100|188.43
09:30:00|100|188.42
09:30:00|500|188.43

【问题讨论】:

    标签: python math pandas stocks


    【解决方案1】:

    您可以将Price 列四舍五入,将它们存储在(临时)approx 列中,然后执行groupby/agg operation

    df['approx'] = df['Price'].round(2)
    df.groupby('approx')['Volume'].sum()
    

    产量

    # approx
    # 188.40     100
    # 188.41    1600
    # 188.42    2339
    # 188.43    1600
    # 188.44     100
    # Name: Volume, dtype: int64
    

    或者,您可以放弃 approx 列并直接将值提供给 df.groupby

    In [142]: df.groupby(df['Price'].round(2))['Volume'].sum()
    Out[142]: 
    Price
    188.40     100
    188.41    1600
    188.42    2339
    188.43    1600
    188.44     100
    Name: Volume, dtype: int64
    

    【讨论】:

    • 谢谢!我什至不知道 groupby
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多