【发布时间】:2018-03-08 06:08:03
【问题描述】:
我有一个 2 列数据框(数量和价格),我想基于体积列创建 20 个 bin,每个 bin 中的数据量相等。
即如果我得到 volume = [1,6,8,2,6,9,3,6] 和 4 个 bin,我想将数据剪切到第一个 bin:1:2,第二个:3:6,第三个:6: 8、4:8:9
然后绘制对应 y 值的平均直方图
我的资料:
df = pd.DataFrame{'Volume_norm' : [0.92, 2.31, 0.92, 0.018, 0.0454, 0.43, 0.43,0.943,0.543,0.543,0.43] , 'Price' : [2, 4, 5, 1, 5, 1, 2, 4, 2, 3, 6]}
我的代码:
x = sorted(FilteredTrade_buy['Volume_norm'])
bins=x[0::int(len(x)/50)]
n, bins, patches = plt.hist(x, bins=bins)
plt.show()
它只给了我 x(数量)的总和,而不是平均 y 价格
===============更新代码==============
df = pd.DataFrame({'Volume_norm' : [0.92,2.31,0.92,0.018,0.0454,0.43,0.43,0.943,0.543,0.543,0.43],
'Price' : [2,4,5,1,5,1,2,4,2,3,6]})
x = df['Volume_norm']
y = df['Price']
nbins = 5
binsize = x.size // nbins
indices = x.argsort()
means = np.zeros((nbins,))
xaxis = np.zeros((nbins,))
for k in range(nbins):
xaxis[k] = x[indices[i * binsize : (i + 1) * binsize]].mean()
for i in range(nbins):
means[i] = y[indices[i * binsize : (i + 1) * binsize]].mean()
plt.loglog(xaxis,means,'r-')
plt.show()
但是 xaxis 返回我:array([ 0.9315, 0.9315, 0.9315, 0.9315, 0.9315])
另外,是否可以使用'Counter'来统计每个区间的数据个数?
【问题讨论】:
-
请您将您的数据添加为文本好吗?从图片中复制数据并不容易。
-
等等,所以您希望由
x填充的直方图箱的高度来反映y的平均值?这根本不是直方图,因此您不应该使用假定“直方图”的标准定义的hist函数。也许只需计算y-averages 并使用plt.plot()调用绘制数据 -
问题已编辑(日期 = df);是的,我试图在 plt.plot 中对数据进行分箱,但结果发现分箱的某些边界/边缘是相同的,因此“剪切”功能不起作用
标签: python pandas plot histogram