bin 3d 指向 python 中的 3d bin

bin 3d points into 3d bins in python

如何将 3d 点分箱到 3d 箱中? np.digitize有没有多维版本? 我可以为每个维度单独使用 np.digitize,例如 here。有更好的解决方案吗? 谢谢!

您可以使用 numpy.histogramdd(sample) 执行此操作,其中每个方向的 bin 数量和物理范围都可以像一维直方图一样进行调整。有关参考 page. For more general statistics, like the mean of another variable per point in a bin, you can use the scipy scipy.stats.binned_statistic_dd function, see docs 的更多信息。 对于三维点数组的情况,您可以按以下方式使用它,

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from scipy import stats


#Setup some dummy data
points = np.random.randn(1000,3)
hist, binedges = np.histogramdd(points, normed=False)

#Setup a 3D figure and plot points as well as a series of slices
fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.plot(points[:,0],points[:,1],points[:,2],'k.',alpha=0.3)

#Use one less than bin edges to give rough bin location
X, Y = np.meshgrid(binedges[0][:-1],binedges[1][:-1])

#Loop over range of slice locations (default histogram uses 10 bins)
for ct in [0,2,5,7,9]: 
    cs = ax1.contourf(X,Y,hist[:,:,ct], 
                      zdir='z', 
                      offset=binedges[2][ct], 
                      level=100, 
                      cmap=plt.cm.RdYlBu_r, 
                      alpha=0.5)

ax1.set_xlim(-3, 3)
ax1.set_ylim(-3, 3)
ax1.set_zlim(-3, 3)
plt.colorbar(cs)
plt.show()

它给出了每个位置的一系列直方图切片,