我有一件简单的事情要做,但我仍然没有成功使用 numpy mggrid&meshgrid。 我有一个包含 100 个元素的 numpy 向量:
[0,0,0...0]
我想创建一个 1000x100
像这样的 numpy 数组,每次将向量值之一增加 0.1
,当达到 1.0
时切换到下一个向量值。
所以,第一次迭代应该给我:
[0.1 0 0..0]
[0.2 0 0..0]
.
.
[0.9 0 0..0]
[1.0 0 0..0]
从现在开始,我应该迭代第二个向量数,保留以前的值:
[1.0 0.1 0 0..0]
[1.0 0.2 0 0..0]
[1.0 0.3 0 0..0]
等等。最终的矩阵应该类似于 1000x100,但我不需要将所有值放在一个大的 numpy 数组中 - 它足以迭代并在每次迭代时生成相应的向量。 提前致谢!
最佳答案
这是一种使用初始化
和np.maximum.accumulate
的方法-
def create_stepped_cols(n): # n = number of cols
out = np.zeros((n,10,n))
r = np.linspace(0.1,1.0,10)
d = np.arange(n)
out[d,:,d] = r
out.shape = (-1,n)
np.maximum.accumulate(out, axis=0, out = out)
return out
示例运行 -
In [140]: create_stepped_cols(3)
Out[140]:
array([[ 0.1, 0. , 0. ],
[ 0.2, 0. , 0. ],
[ 0.3, 0. , 0. ],
[ 0.4, 0. , 0. ],
[ 0.5, 0. , 0. ],
[ 0.6, 0. , 0. ],
[ 0.7, 0. , 0. ],
[ 0.8, 0. , 0. ],
[ 0.9, 0. , 0. ],
[ 1. , 0. , 0. ],
[ 1. , 0.1, 0. ],
[ 1. , 0.2, 0. ],
[ 1. , 0.3, 0. ],
[ 1. , 0.4, 0. ],
[ 1. , 0.5, 0. ],
[ 1. , 0.6, 0. ],
[ 1. , 0.7, 0. ],
[ 1. , 0.8, 0. ],
[ 1. , 0.9, 0. ],
[ 1. , 1. , 0. ],
[ 1. , 1. , 0.1],
[ 1. , 1. , 0.2],
[ 1. , 1. , 0.3],
[ 1. , 1. , 0.4],
[ 1. , 1. , 0.5],
[ 1. , 1. , 0.6],
[ 1. , 1. , 0.7],
[ 1. , 1. , 0.8],
[ 1. , 1. , 0.9],
[ 1. , 1. , 1. ]])
In [141]: create_stepped_cols(100).shape
Out[141]: (1000, 100)
关于python - 如何使用 numpy mggrid 或 meshgrid 来完成这个简单的任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43424364/