【问题标题】:python histogram of the y value with equal number of data(x) in each biny 值的 python 直方图,每个 bin 中具有相同数量的数据(x)
【发布时间】: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


【解决方案1】:

根据 x 值 (volume) 对数据进行间接排序,然后计算具有相同大小的 y 数据 (price) 的每个连续 bin 的平均值。

nbins = 20
binsize = volume.size // nbins
indices = volume.argsort()
means = np.zeros((nbins,))
for i in range(nbins):
    means[i] = price[indices[i * binsize : (i + 1) * binsize]].mean()

您也可以重塑price 数组,然后计算沿轴的平均值(即price[indices].reshape(nbins, -1).mean(axis=-1))。这会更快,但要求您在每个 bin 中拥有完全相同数量的数据。当最后一个 bin 的大小与其他 bin 不同时,循环将处理这种情况。

【讨论】:

  • 非常感谢您的帮助。您能否查看问题的更新部分,因为我也想计算音量的平均值并将其绘制为 x 轴。但是我在计算每个 bin 的平均 x 时遇到了麻烦
  • @bing 看起来您在第一个 for 循环中使用了 i,它尚未定义。您可以计算同一循环内的平均 x 和 y 值。
  • 非常感谢,请问这种情况下'argsort()'的作用是什么?
  • @bing np.argsort() 进行“参数排序”。它返回一个索引数组,该数组将对原始数组进行排序。所以indices[0] 给出volume 中最小值的索引,indices[1] 下一个值,依此类推。
猜你喜欢
  • 2017-01-18
  • 1970-01-01
  • 2020-06-11
  • 1970-01-01
  • 2018-11-14
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 2019-07-08
相关资源
最近更新 更多