具有numpy的网格网格的可变维数

时间:2016-09-16 16:32:31

标签: python numpy

我尝试创建一个具有n维的网格网格。 有没有一种更好的方法来调用带有n个列向量的meshgrid,而不是使用我正在使用的if子句?

编辑:目标是将其用于用户定义的n(2-100)而无需编写100 if子句。

if子句中的第二行减少了网格,因此列(n)<列(n + 1)

示例:

import numpy as np
dimension = 2
range = np.arange(0.2,2.4,0.1)
if dimension == 2:
    grid = np.array(np.meshgrid(range,range)).T.reshape(-1,dimension)
    grid = np.array(grid[[i for i in range(grid.shape[0]) if grid[i,0]<grid[i,1]]])
 elif dimension == 3:
     grid = np.array(np.meshgrid(range,range,range)).T.reshape(-1,dimension)
     grid = np.array(grid[[i for i in range(grid.shape[0]) if grid[i,0]<grid[i,1]]])
     grid = np.array(grid[[i for i in range(grid.shape[0]) if grid[i,1]<grid[i,2]]])

编辑:解决方案发布在下面:

dimension = 2
r = np.arange(0.2,2.4,0.1)
grid=np.array(np.meshgrid(*[r]*n)).T.reshape(-1,n)

for i in range(0,n-1):
    grid = np.array([g for g in grid if g[i]<g[i+1]])

1 个答案:

答案 0 :(得分:1)

我还没有完全吸收你的方法和目标,但这是一个部分简化

In [399]: r=np.arange(3)           # simpler range for example
In [400]: grid=np.meshgrid(*[r]*2)   # use `[r]*3` for 3d case
In [401]: grid=np.array(grid).T.reshape(-1,2)
In [402]: np.array([g for g in grid if g[0]<g[1]])  # simpler comprehensions
Out[402]: 
array([[0, 1],
       [0, 2],
       [1, 2]])

itertools.product使2列网格更容易:

In [403]: from itertools import product
In [404]: np.array([g for g in product(r,r) if g[0]<g[1]])
Out[404]: 
array([[0, 1],
       [0, 2],
       [1, 2]])

也就是说,过滤之前的grid

In [407]: grid
Out[407]: 
array([[0, 0],
       [0, 1],
       [0, 2],
       [1, 0],
       [1, 1],
       [1, 2],
       [2, 0],
       [2, 1],
       [2, 2]])

product

In [406]: list(product(r,r))
Out[406]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

product有一个repeat参数,可以让这更容易:

In [411]: list(product(r,repeat=2))
Out[411]: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

您仍然需要if子句对dim = 3应用2步过滤。我想这可以迭代写出

for i in range(0,dimension-1):
   grid = [g for g in grid if g[i]<g[i+1]]