Pandas: need to count the number of values of a column between 0 and 0.001 then 0.001 and 0.002 etc

随声附和 提交于 2019-12-12 06:56:43

问题


My code so far looks like this:

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%'])
ranges = (0, 0.05, 0.1, 0.15 ,0.2, 0.25, 0.3, 0.35, 0.4)
all_onbservations = df['CPA%'].groupby(pd.cut(df['CPA%'], ranges)).count()

I can count them for a specific range but not for an incremental one (between 0 to 0.001 then 0.001 to 0.002 to infinite)... any idea?


回答1:


For consistently separated groups, you can use floor division to construct a grouper:

np.random.seed(0)

df = pd.DataFrame({'A': np.random.random(100) * 0.5})

step = 0.05
res = df.groupby(df['A'] // step).size()
res.index *= step

print(res)

A
0.00    12
0.05    13
0.10     9
0.15     7
0.20    10
0.25    11
0.30    15
0.35     8
0.40     6
0.45     9
dtype: int64


来源:https://stackoverflow.com/questions/53962012/pandas-need-to-count-the-number-of-values-of-a-column-between-0-and-0-001-then

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!