Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用随机数填充的Numpy数组,以便沿x/y轴仅更改一个值_Python_Arrays_Numpy_Random - Fatal编程技术网

Python 用随机数填充的Numpy数组,以便沿x/y轴仅更改一个值

Python 用随机数填充的Numpy数组,以便沿x/y轴仅更改一个值,python,arrays,numpy,random,Python,Arrays,Numpy,Random,我知道如何创建一个用随机数填充的numpy数组,例如:np.random.randint(01100,(5,5)) 但是如何创建一个充满随机数的numpy数组,使两个相邻单元格之间的差值小于等于1 谢谢每行可以相差1。因此,产生一系列差异: In [83]: H, W = 5, 5 In [84]: np.random.randint(-1, 2, size=(H,1)) Out[84]: array([[ 1], [-1], [-1], [-1],

我知道如何创建一个用随机数填充的numpy数组,例如:
np.random.randint(01100,(5,5))

但是如何创建一个充满随机数的numpy数组,使两个相邻单元格之间的差值小于等于1


谢谢

每行可以相差1。因此,产生一系列差异:

In [83]: H, W = 5, 5

In [84]: np.random.randint(-1, 2, size=(H,1))
Out[84]: 
array([[ 1],
       [-1],
       [-1],
       [-1],
       [ 0]])
现在求出累计金额:

In [85]: np.add.accumulate([[ 1], [-1], [-1], [-1], [ 0]])
Out[85]: 
array([[ 1],
       [ 0],
       [-1],
       [-2],
       [-2]])
In [86]: np.add.accumulate(np.random.randint(-1, 2, size=(1,W)), axis=1)
Out[86]: array([[1, 1, 2, 1, 1]])
类似地,每列可以相差1。所以再次产生一系列的差异, 并找出累计金额:

In [85]: np.add.accumulate([[ 1], [-1], [-1], [-1], [ 0]])
Out[85]: 
array([[ 1],
       [ 0],
       [-1],
       [-2],
       [-2]])
In [86]: np.add.accumulate(np.random.randint(-1, 2, size=(1,W)), axis=1)
Out[86]: array([[1, 1, 2, 1, 1]])
现在将这两个累计总和相加。广播创建二维阵列:

import numpy as np

H, W = 5, 5
x = np.add.accumulate(np.random.randint(-1, 2, size=(H,1)), axis=0)
y = np.add.accumulate(np.random.randint(-1, 2, size=(1,W)), axis=1)
out = x + y
print(out)
打印随机数组,例如

[[ 1  0 -1  0 -1]
 [ 2  1  0  1  0]
 [ 3  2  1  2  1]
 [ 3  2  1  2  1]
 [ 2  1  0  1  0]]

您可以将常量添加到此数组中,以生成具有相同属性的其他随机数组。

“每个单元格周围仅更改一个”请再说一遍?你是说两个相邻单元格之间的差值是1还是更小?没错,我是说这个。更新帖子…不要认为你可以用np.random或类似的。使用for循环创建数组,并跟踪每个创建的数组的当前值,有1/3的机会递增、递减或保持不变。1D数组听起来很简单,但2D单元格呢?这变得非常棘手。我想知道numpy数组上是否存在类似列表理解的功能,以避免嵌套循环…这是解决我问题的有效方法。