Python -在2D网格上划分x,y,z值



我有一个z点与配对x,y相关联的列表,这意味着例如

x     y                    z
3.1   5.2                  1.3    
4.2   2.3                  9.3
5.6   9.8                  3.5

等等。z值的总数比较高,大约在10000左右。我想按以下方式存放我的数据:

1)我想把xy的值分割成单元格,以便在x,y中制作一个二维网格。如果我在x轴上有Nx单元格,在y轴上有Ny单元格,那么我将在网格上有Nx*Ny单元格。例如,x的第一个bin的范围可以是1。2。, 2的第二个。为3。等等。

2)对于二维网格中的每个单元格,我需要计算有多少个点落在该单元格中,并将所有z值相加。这给了我一个与每个单元格相关联的数值。

我想使用binned_statisticscipy.stats,但我不知道如何设置选项来完成我的任务。有什么建议吗?此外,binned_statistic以外的其他工具也被广泛接受。

假设我理解了,您可以通过利用binned_statistic_2dexpand_binnumbers参数获得所需的内容,因此。

from scipy.stats import binned_statistic_2d
import numpy as np
x = [0.1, 0.1, 0.1, 0.6]
y = [2.1, 2.6, 2.1, 2.1]
z = [2.,3.,5.,7.]
binx = [0.0, 0.5, 1.0]
biny = [2.0, 2.5, 3.0]
ret = binned_statistic_2d(x, y, None, 'count', bins=[binx,biny], 
    expand_binnumbers=True)
print (ret.statistic)
print (ret.binnumber)
sums = np.zeros([-1+len(binx), -1+len(biny)])
for i in range(len(x)):
    m = ret.binnumber [0][i] - 1
    n = ret.binnumber [1][i] - 1
    sums[m][n] += sums[m][n] + z[i]
print (sums)

这只是其中一个例子的展开。输出如下:

[[ 2.  1.]
 [ 1.  0.]]
[[1 1 1 2]
 [1 2 1 1]]
[[ 9.  3.]
 [ 7.  0.]]

建立单元格的边缘,遍历单元格边缘并使用布尔索引提取每个单元格中的z值,将总和保存在列表中,转换列表并重塑它。

import itertools
import numpy as np
x = np.array([0.1, 0.1, 0.1, 0.6, 1.2, 2.1])
y = np.array([2.1, 2.6, 2.1, 2.1, 3.4, 4.7])
z = np.array([2., 3., 5., 7., 10, 20])

def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)
minx, maxx = int(min(x)), int(max(x)) + 1
miny, maxy = int(min(y)), int(max(y)) + 1
result = []
x_edges = pairwise(xrange(minx, maxx + 1))
for xleft, xright in x_edges:
    xmask = np.logical_and(x >= xleft, x < xright)
    y_edges = pairwise(xrange(miny, maxy + 1))
    for yleft, yright in y_edges:
        ymask = np.logical_and(y >= yleft, y < yright)
        cell = z[np.logical_and(xmask, ymask)]
        result.append(cell.sum())
result = np.array(result).reshape((maxx - minx, maxy - miny))

>>> result
array([[ 17.,   0.,   0.],
       [  0.,  10.,   0.],
       [  0.,   0.,  20.]])
>>> 

不幸的是,没有numpy矢量化魔法

最新更新