如何递增numpy数组中的值?

2024-06-16 11:41:13 发布

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

我用相同的值填充了一个数组,但是,我希望该值每行递增减少0.025。目前看起来是这样的:

import numpy as np

vp_ref = 30
surf_lay = np.ones(([1000,10000]), dtype=np.float32);
gvp_ref = vp_ref * surf_lay

因此数组中填充了30秒。我希望第一行是30,下一行减少到29.975,一直到底部。我该怎么做


Tags: importnumpyrefasnpones数组surf
3条回答

可以使用np.linspace创建线性间隔的数据,然后使用np.tile创建二维数组:

n = 1000
tmp = np.linspace(30, 30 - (n-1)*0.025, n)
result = np.tile(tmp[:, None], (1, 10_000))

这里,在这个代码中,alpha是0.025

import numpy as np
vp_ref = 30
surf_lay = np.ones(([1000,10000]), dtype=np.float32);
gvp_ref = vp_ref * surf_lay

alpha = 0.025
substration_array = np.array([[alpha*i]*gvp_ref.shape[1] for i in range(gvp_ref.shape[0])])

gvp_ref.shape
substration_array.shape

output = np.subtract(gvp_ref, substration_array)

这里有一个解决方案:

  1. 定义step_range以获取从0开始的所有值,添加step直到矩阵大小结束
  2. 减去它
step = 0.025
step_range = np.arange(0, gvp_ref.shape[0] * step, step).reshape(-1, 1)
print(gvp_ref - step_range)

输出:

array([[30.   , 30.   , 30.   , ..., 30.   , 30.   , 30.   ],
       [29.975, 29.975, 29.975, ..., 29.975, 29.975, 29.975],
       [29.95 , 29.95 , 29.95 , ..., 29.95 , 29.95 , 29.95 ],
       ...,
       [ 5.075,  5.075,  5.075, ...,  5.075,  5.075,  5.075],
       [ 5.05 ,  5.05 ,  5.05 , ...,  5.05 ,  5.05 ,  5.05 ],
       [ 5.025,  5.025,  5.025, ...,  5.025,  5.025,  5.025]])

相关问题 更多 >