2016-11-13 49 views
1

我有z点的列表相关联,以对x,y,这意味着z值即例如的Python - 分级X,Y,在2D网格

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值分裂成细胞,从而使如果我有Nx轴的x轴和Nyy轴,我会在网格上有Nx*Ny单元格。例如,x的第一个bin可以从1到2,第二个从2到3.等等。

2)对于2维网格中的每个单元格,我需要计算该单元格中有多少个点,并将其所有值计算出来。这给了我一个与每个细胞相关的数值。

我想过使用binned_statisticscipy.stats,但我不知道如何设置选项来完成我的任务。有什么建议么?除了binned_statistic之外,其他工具也很受欢迎。

回答

1

假设我明白了,你可以得到你所需要的通过利用expand_binnumbers参数binned_statistic_2d,因此。

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.]] 
1

建立的细胞边缘,迭代小区边缘,并在每个单元使用布尔索引,以提取的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的矢量魔法