gpt4 book ai didi

python - 连接、排序和重新分区 xyz 数据

转载 作者:行者123 更新时间:2023-11-28 22:13:01 25 4
gpt4 key购买 nike

我遇到这样一种情况,我有两个 [x, y, z] 数据列表,我想连接这些列表,对它们进行排序,然后提取 z 值的矩阵,其中 x 沿列递增,y沿行增加。

举个例子:

list1 = np.linspace(-2,2,3)
list2 = np.linspace(-1,1,3)

dat1 = []
for x in list1:
for y in list1:
z = x * y
dat1 += [[x,y,z]]

dat1 = np.array(dat1)

dat2 = []
for x in list2:
for y in list2:
z = x * y
dat2 += [[x,y,z]]

dat2 = np.array(dat2)

我可以使用以下方法分别从每个列表的 z 值构建一个数组:

dat1[:, 2].reshape((list1.shape[0],list1.shape[0]))

但我想要一个(有序的)数组来存储两个列表中的所有值,即我想对完全排序的数据集做同样的事情:

dat_full=np.vstack((dat1, dat2))
dat_index = np.lexsort((dat_full[:,1], dat_full[:,0]))
dat_sorted = dat_full[dat_index]

问题是这不再是方形数组,所以我不能使用我之前使用的简单 reshape 技巧。有什么好的方法吗?

编辑:

我应该澄清一下,我只对串联数组中的唯一数据感兴趣,可以使用以下方法找到:

dat_full=np.unique(np.vstack((dat1, dat2)))
dat_index = np.lexsort((dat_full[:,1], dat_full[:,0]))
dat_sorted = dat_full[dat_index]

最佳答案

markuscosinus说,这个问题是你需要一个具有不同行和列大小的“矩阵”,这在 NumPy 中是做不到的。但是,您可以考虑的替代方法是使用 masked array ,如果你能处理的话。这将允许您将所有值都放在同一个数组中并将“间隙”屏蔽为无效。例如,您可以这样做(我已经更改了创建 dat1dat2 的方式,但结果是一样的):

import numpy as np

list1 = np.linspace(-2, 2, 3)
list2 = np.linspace(-1, 1, 3)
# Evaluate using grids instead of loops
xg1, yg1 = np.meshgrid(list1, list1, indexing='ij')
x1, y1 = xg1.ravel(), yg1.ravel()
xg2, yg2 = np.meshgrid(list2, list2, indexing='ij')
x2, y2 = xg2.ravel(), yg2.ravel()
dat1 = np.stack([x1, y1, x1 * y1], axis=-1)
dat2 = np.stack([x2, y2, x2 * y2], axis=-1)
# Full dataset
dat_full = np.concatenate([dat1, dat2])
# Remove repeated rows
_, idx = np.unique(dat_full, return_index=True, axis=0)
dat_uniq = dat_full[idx]
# Find unique X and Y values
_, x_idx, x_counts = np.unique(dat_uniq[:, 0], return_inverse=True, return_counts=True)
_, y_idx, y_counts = np.unique(dat_uniq[:, 1], return_inverse=True, return_counts=True)
# Make array as big as the most repeated index
result = np.zeros((x_counts.max(), y_counts.max()), dtype=dat_full.dtype)
# Make mask for array
mask = np.ones_like(result, dtype=bool)
# Fill array and mask
result[x_idx, y_idx] = dat_uniq[:, 2]
mask[x_idx, y_idx] = False
# Make masked array
result = np.ma.masked_array(result, mask)
print(result)

输出:

[[4.0 -- -0.0 -- -4.0]
[-- 1.0 -0.0 -1.0 --]
[-0.0 -0.0 0.0 0.0 0.0]
[-- -1.0 0.0 1.0 --]
[-4.0 -- 0.0 -- 4.0]]

关于python - 连接、排序和重新分区 xyz 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54362961/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com