我是一个完全迷失的新手,他的目标是编写一个脚本来创建一个随机整数网格,其中用户输入指定行数、列数、最高值和最低值以及生成的步骤对最高值和最低值之间的值进行计数(例如从 0 到 10 按两位数计数)。使用该输入,然后用随机生成的符合条件的整数填充网格。我知道我可以使用“np.arange”来设置范围和步长值,然后使用调整大小将数组调整为正确的大小,但我完全坚持的是一次获取数组中其余的 0 值它被调整大小以适应范围和步长值。我该怎么做呢?到目前为止我的代码:
num_rows = int(raw_input("How many rows in the raster? "))
num_cols = int(raw_input("How many columns in the raster? "))
low_range = int(raw_input("What is the lowest value in the raster? "))
hi_range = int(raw_input("What is the highest value in the raster? "))
step_range = int(raw_input("What is the value step you would like? "))
user_raster = np.arange(low_range,hi_range,step_range)
user_raster2 = user_raster.resize((num_rows, num_cols), refcheck=False)
使用 5 行、5 列、低值为 0、高值为 10、步长为 2 的结果运行此程序
[[0 2 4 6 8]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]
[0 0 0 0 0]]
那么我该如何以 2 为步长将 0 替换为 0-10 的值呢?我知道有“追加”和“插入”等选项,但这些选项并没有给我以阶梯式执行此操作的选项。
或者(很可能)有更好的方法来解决这个问题?我意识到的一个关键缺陷是,高值高于行数,那么随机生成时,顶部值范围将被截断并且不会放置在网格中。最佳答案
您的 user_raster
数组在示例中只有 5 个元素长,当您将其大小调整为 5x5 时,np.ndarray.resize
会用零填充额外的空间。您可以使用np.resize
(为ndarray.resize
行为添加强调):
Definition: np.resize(a, new_shape)
Docstring: Return a new array with the specified shape.
If the new array is larger than the original array, then the new array is filled with repeated copies of
a
. Note that this behavior is different from a.resize(new_shape) which fills with zeros instead of repeated copies ofa
.
rows = 5
cols = 5
low = 0
hi = 10
step = 2
user_raster = np.arange(low, hi, step)
# array([0, 2, 4, 6, 8])
user_raster2 = np.resize(user_raster, (rows, cols))
# Output:
array([[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8]])
可用于此类数组的一个技巧是使用np.mgrid
:
low = 0
hi = 10
step = 2
axis = 1 # horizontal
np.mgrid[low:hi:step, low:hi:step][axis]
# Output:
array([[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8],
[0, 2, 4, 6, 8]])
关于python - 创建特定大小的 Numpy 数组,然后以步进速率填充值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28981059/