2016-11-13 48 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的矢量魔法