【问题标题】:Pandas: count the values for a range of 0.001, so count between 0 to 0.001 then count between 0.001 and 0.002 etcPandas:计算 0.001 范围内的值,所以在 0 到 0.001 之间计数,然后在 0.001 和 0.002 之间计数,等等
【发布时间】:2018-12-29 23:47:12
【问题描述】:

我想按特定范围(0,1;0,2;等)对我的值 (CPA%) 进行分组。 现在我的代码看起来像:

 conn = psycopg2.connect("dbname=monty user=postgres host=localhost password=postgres")
cur = conn.cursor()
cur.execute("SELECT * FROM binance.zrxeth_ob_indicators;")
row = cur.fetchall()
df = pd.DataFrame(row,columns=['timestamp', 'topAsk', 'topBid', 'CPA', 'midprice', 'CPB', 'spread', 'CPA%', 'CPB%'])
pd.cut(df,0.001)

我的输出如下:

CPA%
0.005822
0.007129
0.008345
0.022531
0.016073
0.013433
0.013616
0.016571

如何按特定范围按这些值分组并计算它们?我对库 pandas 不太熟悉,并且不正确理解如何使用它...

【问题讨论】:

标签: python pandas


【解决方案1】:

这里不需要cut,使用//value_counts

(df['CPA%']//0.001).value_counts()
Out[628]: 
13.0    2
16.0    2
22.0    1
8.0     1
7.0     1
5.0     1
Name: CPA%, dtype: int64

让我们尝试另一种选择

import numpy as np 

np.floor(df['CPA%']*1000).value_counts()
Out[637]: 
13.0    2
16.0    2
22.0    1
8.0     1
7.0     1
5.0     1
Name: CPA%, dtype: int64
-

【讨论】:

  • 我有那个“TypeError: unsupported operand type(s) for //: 'Decimal' and 'float'”,它来自 pandas 数据框吗?
  • @Viktor.w 你的熊猫版本是什么?
  • 我有以下版本:u'0.23.4'
【解决方案2】:

我不确定这是否能回答您的问题,但一个快速的解决方案是在 pandas 中创建一个新列,您可以在其中创建范围组。比如:

df.loc[:,'range_group'] = np.where(df.CPA >0.75, 1, np.where(df.CPA > 0.5, 2, np.where(df.CPA> 0.25, 3, 4)))

然后你做一个 groupby,例如,计算每个范围组上的行数:

df.groupby('range_group').CPA.count() 

只需将 count() 更改为您想要的任何功能。 这是你想要的吗?

根据您在下面的评论,您似乎需要这个:

steps = [0,0.001, 0.002, 0.003, ....,1]
df.groupby(pd.cut(df.CPA, steps)).count()

【讨论】:

  • 是的或多或少,实际上我想计算 0 到 0.001 之间的每个值,然后计算 0.001 到 0.002 之间的每个值等等......
  • 检查我的编辑。我认为添加的脚本可以满足您的需求。
猜你喜欢
  • 2019-05-26
  • 1970-01-01
  • 2013-03-22
  • 2013-08-15
  • 2014-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-05
相关资源
最近更新 更多