gpt4 book ai didi

python - 将 numpy 开放网格转换为坐标

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:56 25 4
gpt4 key购买 nike

我想将 numpy ix_ 例程返回的开放网格转换为坐标列表

例如,对于:

In[1]: m = np.ix_([0, 2, 4], [1, 3])
In[2]: m
Out[2]:
(array([[0],
[2],
[4]]), array([[1, 3]]))

我想要的是:

([0, 1], [0, 3], [2, 1], [2, 3], [4, 1], [4, 3])

我很确定我可以通过一些迭代、解包和压缩来破解它,但我确定必须有一种聪明的 numpy 方法来实现这一点......

最佳答案

方法 #1 使用 np.meshgrid然后堆叠 -

r,c = np.meshgrid(*m)
out = np.column_stack((r.ravel('F'), c.ravel('F') ))

方法 #2 或者,使用 np.array() 然后是 transposingreshaping -

np.array(np.meshgrid(*m)).T.reshape(-1,len(m))

对于在 np.ix_ 中使用通用数组数量的通用案例,这里是需要的修改 -

p = np.r_[2:0:-1,3:len(m)+1,0]
out = np.array(np.meshgrid(*m)).transpose(p).reshape(-1,len(m))

样本运行-

两个数组的情况:

In [376]: m = np.ix_([0, 2, 4], [1, 3])

In [377]: p = np.r_[2:0:-1,3:len(m)+1,0]

In [378]: np.array(np.meshgrid(*m)).transpose(p).reshape(-1,len(m))
Out[378]:
array([[0, 1],
[0, 3],
[2, 1],
[2, 3],
[4, 1],
[4, 3]])

三个数组的情况:

In [379]: m = np.ix_([0, 2, 4], [1, 3],[6,5,9])

In [380]: p = np.r_[2:0:-1,3:len(m)+1,0]

In [381]: np.array(np.meshgrid(*m)).transpose(p).reshape(-1,len(m))
Out[381]:
array([[0, 1, 6],
[0, 1, 5],
[0, 1, 9],
[0, 3, 6],
[0, 3, 5],
[0, 3, 9],
[2, 1, 6],
[2, 1, 5],
[2, 1, 9],
[2, 3, 6],
[2, 3, 5],
[2, 3, 9],
[4, 1, 6],
[4, 1, 5],
[4, 1, 9],
[4, 3, 6],
[4, 3, 5],
[4, 3, 9]])

关于python - 将 numpy 开放网格转换为坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43228347/

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