用python创建等间距网格

2024-09-30 20:21:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我知道必须有更好的方法来实现这一点,尤其是使用numpy,而且不需要附加到数组。在python中有没有一种更简洁的方法来完成类似的操作?在

def create_uniform_grid(low, high, bins=(10, 10)):
    """Define a uniformly-spaced grid that can be used to discretize a space.

    Parameters
    ----------
    low : array_like
        Lower bounds for each dimension of the continuous space.
    high : array_like
        Upper bounds for each dimension of the continuous space.
    bins : tuple
        Number of bins along each corresponding dimension.

    Returns
    -------
    grid : list of array_like
        A list of arrays containing split points for each dimension.
    """
    range1 = high[0] - low[0]
    range2 = high[1] - low[1]

    steps1 = range1 / bins[0]
    steps2 = range2 / bins[1]

    arr1 = []
    arr2 = []

    for i in range(0, bins[0] - 1):
        if(i == 0):
            arr1.append(low[0] + steps1)
            arr2.append(low[1] + steps2)
        else:
            arr1.append(round((arr1[i - 1] + steps1), 1))
            arr2.append(arr2[i - 1] + steps2)

    return [arr1, arr2]


low = [-1.0, -5.0]
high = [1.0, 5.0]
create_uniform_grid(low, high)

# [[-0.8, -0.6, -0.4, -0.2, 0.0, 0.2, 0.4, 0.6, 0.8],
# [-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0]]

Tags: offorspacearraygridlikeloweach
2条回答

np.ogrid与您的函数类似。区别:1)它将保留端点;2)它将创建一列和一行,因此其输出为“广播就绪”:

    >>> np.ogrid[-1:1:11j, -5:5:11j]
[array([[-1. ],
       [-0.8],
       [-0.6],
       [-0.4],
       [-0.2],
       [ 0. ],
       [ 0.2],
       [ 0.4],
       [ 0.6],
       [ 0.8],
       [ 1. ]]), array([[-5., -4., -3., -2., -1.,  0.,  1.,  2.,  3.,  4.,  5.]])]

也许numpy.meshgrid就是你想要的。在

下面是一个创建网格并对其进行数学运算的示例:

#!/usr/bin/python3
# 2018.04.11 11:40:17 CST

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-5, 5, 0.1)
y = np.arange(-5, 5, 0.1)
xx, yy = np.meshgrid(x, y, sparse=True)
z = np.sin(xx**2 + yy**2) / (xx**2 + yy**2)
#h = plt.contourf(x,y,z)

plt.imshow(z)
plt.show()

enter image description here


参考:

  1. https://docs.scipy.org/doc/numpy/reference/generated/numpy.meshgrid.html

相关问题 更多 >