首页 > 解决方案 > Python pandas,按X大小对列进行数据分箱

问题描述

为订单簿获取数据时,我以这种格式获取

    Price    Size
--------------------
0   8549.61  0.107015
1   8549.32  0.100000
2   8549.31  0.060000
3   8548.66  0.013950
4   8548.65  0.064791
... ... ...
995 8401.40  0.313921
996 8401.19  0.767512
997 8401.17  0.001721
998 8401.10  0.166487
999 8401.03  0.002235

1000 rows × 2 columns

有没有办法将每 10 美元的价格值组合起来,并且大小将是该范围的总和?

例如

    Price   Size
--------------------
0   8550    0.107015
1   8560    0.100000
2    870    0.060000
3   8580    0.013950

我正在查看分箱,但这给了我奇怪的结果,在此先感谢!

标签: pythonpandas

解决方案


您可以使用它Pandas来执行此操作。

df['Price'] = df['Price'].astype(str)
#determine the length inorder to modify the significant digit
len_str=len(str(int(float(df['Price'][0]))))

df['binned'] = df.groupby(df.Price.str[0:len_str-1])['Size'].transform('sum')
df['column'] = df.Price.str[0:len_str-1]+'0'

df=df.drop_duplicates(subset=['column', 'binned'])[['column','binned']].reset_index(drop=True)

推荐阅读