建立从二维坐标数组numpy的 [英] Make 2D Numpy array from coordinates

查看:1376
本文介绍了建立从二维坐标数组numpy的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重新的二维数组(矩阵)present一个坐标数据点。点定期网格化,所不同的是数据点是从一些网格位置缺失。

I have data points that represent a coordinates for a 2D array (matrix). The points are regularly gridded, except that data points are missing from some grid positions.

例如,假设在常规网格0.1与适合一些形状XYZ数据(3,4)。有差距和失分,所以有5分,而不是12:

For example, consider some XYZ data that fits on a regular 0.1 grid with shape (3, 4). There are gaps and missing points, so there are 5 points, and not 12:

import numpy as np
X = np.array([0.4, 0.5, 0.4, 0.4, 0.7])
Y = np.array([1.0, 1.0, 1.1, 1.2, 1.2])
Z = np.array([3.3, 2.5, 3.6, 3.8, 1.8])
# Evaluate the regular grid dimension values
Xr = np.linspace(X.min(), X.max(), np.round((X.max() - X.min()) / np.diff(np.unique(X)).min()) + 1)
Yr = np.linspace(Y.min(), Y.max(), np.round((Y.max() - Y.min()) / np.diff(np.unique(Y)).min()) + 1)
print('Xr={0}; Yr={1}'.format(Xr, Yr))
# Xr=[ 0.4  0.5  0.6  0.7]; Yr=[ 1.   1.1  1.2]

我想看到什么显示此图像中(背景:黑色=基础0指数;灰色=坐标值;彩色矩阵=价值;白色=丢失)

What I would like to see is shown in this image (backgrounds: black=base-0 index; grey=coordinate value; colour=matrix value; white=missing).

下面是我有什么,这是直观的一个for循环:

Here's what I have, which is intuitive with a for loop:

ar = np.ma.array(np.zeros((len(Yr), len(Xr)), dtype=Z.dtype), mask=True)
for x, y, z in zip(X, Y, Z):
    j = (np.abs(Xr -  x)).argmin()
    i = (np.abs(Yr -  y)).argmin()
    ar[i, j] = z
print(ar)
# [[3.3 2.5 -- --]
#  [3.6 -- -- --]
#  [3.8 -- -- 1.8]]    

有没有向量化的办法更NumPythonic方法返回一个二维数组 AR ?抑或是循环必要吗?

推荐答案

您可以做到这一点与<单行href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram2d.html\"><$c$c>np.histogram2d

You can do it on one line with np.histogram2d

data = np.histogram2d(Y, X, bins=[len(Yr),len(Xr)], weights=Z)
print(data[0])
[[ 3.3  2.5  0.   0. ]
 [ 3.6  0.   0.   0. ]
 [ 3.8  0.   0.   1.8]]

这篇关于建立从二维坐标数组numpy的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆