out = X*np.nan
for i in range(max(b)):
out[i] = np.nanmean(f[x_grid[b==i], y_grid[b==i]])
은 np.bincount
에 두 통화로 대체 될 수 있습니다
total = np.bincount(b, weights=f[x_grid, y_grid], minlength=len(X))
count = np.bincount(b, minlength=len(X))
out = total/count
또는 하나의 호출 stats.binned_statistic
에 :
out, bin_edges, binnumber = stats.binned_statistic(
x=b, values=f[x_grid, y_grid], statistic='mean', bins=np.arange(len(X)+1))
예를 들어
,
import numpy as np
from scipy.spatial import KDTree
import scipy.stats as stats
np.random.seed(2017)
def rebin(f, X, Y):
s = f.shape
x_grid = np.arange(s[0])
y_grid = np.arange(s[1])
x_grid, y_grid = np.meshgrid(x_grid,y_grid)
x_grid, y_grid = x_grid.flatten(), y_grid.flatten()
tree = KDTree(np.column_stack((X,Y)))
_, b = tree.query(np.column_stack((x_grid, y_grid)))
out, bin_edges, binnumber = stats.binned_statistic(
x=b, values=f[x_grid, y_grid], statistic='mean', bins=np.arange(len(X)+1))
# total = np.bincount(b, weights=f[x_grid, y_grid], minlength=len(X))
# count = np.bincount(b, minlength=len(X))
# out = total/count
return out
def orig(f, X, Y):
s = f.shape
x_grid = np.arange(s[0])
y_grid = np.arange(s[1])
x_grid, y_grid = np.meshgrid(x_grid,y_grid)
x_grid, y_grid = x_grid.flatten(), y_grid.flatten()
tree = KDTree(np.column_stack((X,Y)))
_, b = tree.query(np.column_stack((x_grid, y_grid)))
out = X*np.nan
for i in range(len(X)):
out[i] = np.nanmean(f[x_grid[b==i], y_grid[b==i]])
return out
N = 100
X, Y = np.random.random((2, N))
f = np.random.random((N, N))
expected = orig(f, X, Y)
result = rebin(f, X, Y)
print(np.allclose(expected, result, equal_nan=True))
# True