假设文件中的x和y值直接对应于索引(就像在您的示例中那样),您可以执行与此类似的操作:
import numpy as np
x = [0, 0, 1, 1, 2, 2]
y = [1, 2, 0, 1, 1, 2]
z = [14, 17, 15, 16, 18, 13]
z_array = np.nan * np.empty((3,3))
z_array[y, x] = z
print z_array
产量:
[[ nan 15. nan]
[ 14. 16. 18.]
[ 17. nan 13.]]
对于大型数组,这将比坐标上的显式循环快得多.
处理不均匀的x&输入
如果你经常采样x& y点,然后您可以通过减去网格的“角”(即x0和y0),除以单元格间距,并将其转换为整数,将它们转换为网格索引.然后,您可以使用上述方法或任何其他答案.
作为一般例子:
i = ((y - y0) / dy).astype(int)
j = ((x - x0) / dx).astype(int)
grid[i,j] = z
但是,如果您的数据没有规则间隔,则可以使用一些技巧.
假设我们有以下数据:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)
x, y, z = np.random.random((3, 10))
fig, ax = plt.subplots()
scat = ax.scatter(x, y, c=z, s=200)
fig.colorbar(scat)
ax.margins(0.05)
我们想要放入常规的10×10网格:
我们实际上可以使用/滥用np.histogram2d.而不是计数,我们将它添加落入单元格的每个点的值.最简单的方法是指定weights = z,normed = False.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)
x, y, z = np.random.random((3, 10))
# Bin the data onto a 10x10 grid
# Have to reverse x & y due to row-first indexing
zi, yi, xi = np.histogram2d(y, x, bins=(10,10), weights=z, normed=False)
zi = np.ma.masked_equal(zi, 0)
fig, ax = plt.subplots()
ax.pcolormesh(xi, yi, zi, edgecolors='black')
scat = ax.scatter(x, y, c=z, s=200)
fig.colorbar(scat)
ax.margins(0.05)
plt.show()
但是,如果我们有大量的积分,一些垃圾箱会有不止一个积分. np.histogram的权重参数只是添加了值.在这种情况下,这可能不是你想要的.尽管如此,我们可以通过除以计数得到每个单元格中落点的平均值.
所以,例如,假设我们有50分:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(1977)
x, y, z = np.random.random((3, 50))
# Bin the data onto a 10x10 grid
# Have to reverse x & y due to row-first indexing
zi, yi, xi = np.histogram2d(y, x, bins=(10,10), weights=z, normed=False)
counts, _, _ = np.histogram2d(y, x, bins=(10,10))
zi = zi / counts
zi = np.ma.masked_invalid(zi)
fig, ax = plt.subplots()
ax.pcolormesh(xi, yi, zi, edgecolors='black')
scat = ax.scatter(x, y, c=z, s=200)
fig.colorbar(scat)
ax.margins(0.05)
plt.show()
由于点数非常多,这种精确的方法会变慢(并且可以很容易地加速),但对于小于1e6点的任何东西都足够了.