从三个1D numpy数组填充2D numpy数组 [英] Fill 2D numpy array from three 1D numpy arrays

查看:107
本文介绍了从三个1D numpy数组填充2D numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否存在不使用循环就可以从未排序的坐标点(即并非所有lon和/或lat都是上升或下降)创建值的二维数组的有效方法吗?

Is there an efficient way of creating a 2D array of the values from unsorted coordinate points (i.e. not all lons and/or lats are ascending or descending) without using loops?

示例数据

lats = np.array([45.5,45.5,45.5,65.3,65.3,65.3,43.2,43.2,43.2,65.3])
lons = np.array([102.5,5.5,116.2,102.5,5.5,116.2,102.5,5.5,116.2,100])
vals = np.array([3,4,5,6,7,7,9,1,0,4])

示例输出
每列代表唯一的经度(102.5、5.5、116.2和100),每列代表唯一的经度(45.5、65.3和43.2).

Example Output
Each column represents a unique longitude (102.5, 5.5, 116.2, & 100) and each column represents a unique latitude (45.5,65.3, & 43.2).

([ 3, 4, 5, NaN],
 [ 6, 7, 7, 4],
 [ 9, 1, 0, NaN])

但是,它并不是那么简单,因为我不一定知道每个lon或lat有多少重复项决定了数组的形状.

Though, it isn't so straight forward because I don't necessarily know how many duplicates of each lon or lat there are which determines the shape of the array.

更新:
我为我的问题安排的数据不​​正确.我已经安排好了,所以它们都是唯一的对,还有一个额外的数据点来演示当存在NaN时应该如何安排数据.

Update:
I had the data arranged incorrectly for my question. I have arranged it now, so they are all unique pairs and there is an additional data point to demonstrate how the data should be arranged when NaNs are present.

推荐答案

您发布的示例没有什么意义,并且它不允许任何合理的方法来指定丢失的数据.我在这里猜测,但是您可能要处理的唯一合理的事情似乎是这样的:

The example you have posted makes very little sense, and it doesn't allow any reasonable way to specify missing data. I am guessing here, but the only reasonable thing you may be dealing with seems to be something like this :

>>> lats = np.array([43.2, 43.2, 43.2, 45.5, 45.5, 45.5, 65.3, 65.3, 65.3])
>>> lons = np.array([5.5, 102.5, 116.2, 5.5, 102.5, 116.2, 5.5, 102.5, 116.2])
>>> vals = np.array([3, 4, 5, 6, 7, 7, 9, 1, 0])

vals[j]中的值来自纬度lats[j]和经度lons[j],但是数据可能会变得混乱,例如:

Where the value in vals[j] comes from latitude lats[j] and longitude lons[j], but the data may come scrambled, as in :

>>> indices = np.arange(9)
>>> np.random.shuffle(indices)
>>> lats = lats[indices]
>>> lons = lons[indices]
>>> vals = vals[indices]
>>> lats
array([ 45.5,  43.2,  65.3,  45.5,  43.2,  65.3,  45.5,  65.3,  43.2])
>>> lons
array([   5.5,  116.2,  102.5,  116.2,    5.5,  116.2,  102.5,    5.5,  102.5])
>>> vals
array([6, 5, 1, 7, 3, 0, 7, 9, 4])

您可以将其排列成如下数组:

You can get this arranged into an array as follows:

>>> lat_vals, lat_idx = np.unique(lats, return_inverse=True)
>>> lon_vals, lon_idx = np.unique(lons, return_inverse=True)
>>> vals_array = np.empty(lat_vals.shape + lon_vals.shape)
>>> vals_array.fill(np.nan) # or whatever yor desired missing data flag is
>>> vals_array[lat_idx, lon_idx] = vals
>>> vals_array
array([[ 3.,  4.,  5.],
       [ 6.,  7.,  7.],
       [ 9.,  1.,  0.]])

这篇关于从三个1D numpy数组填充2D numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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