英文:
Sum decimal numbers in numpy array
问题
I need to sum values from different arrays, but the problem is that an array that contains the number 0.5 is recognized just as 0. I need to sum the decimal part of the number (.5) because is to calculate an index.
This is my code
red_band = dataset.read(4)
nir_band = dataset.read(5)
L = np.full_like(red_band, 0.5)
savi = ((nir_band.astype(float) - red_band.astype(float)) / (red_band.astype(float) + nir_band.astype(float) + L))*(np.full_like(red_band, 1) + L)
And this is an example of my output for variable L
array([[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]], dtype=uint16)
英文:
I need to sum values from different arrays, but the problem is that an array that contains the number 0.5 is recognized just as 0. . I need to sum the decimal part of the number (.5) because is to calculate an index.
This is my code
red_band = dataset.read(4)
nir_band = dataset.read(5)
L = np.full_like(red_band, 0.5)
savi = ((nir_band.astype(float) - red_band.astype(float)) / (red_band.astype(float) + nir_band.astype(float) + L))*(np.full_like(red_band, 1) + L)
And this is an example of my ouput for variable L
array([[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
...,
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0],
[0, 0, 0, ..., 0, 0, 0]], dtype=uint16)
答案1
得分: 1
np.full_like
与给定数组的大小和类型相匹配。在这种情况下,red_band
是一个整数数组(具体来说是 uint16
)。尝试使用浮点数(如 0.5
)填充整数数组会导致截断,这就是为什么 L
包含全部为 0
的原因。
要创建一个与 red_band
大小相同的浮点数数组,您可以使用 np.full
替代:
L = np.full(red_band.shape, 0.5)
英文:
np.full_like
matches the size and type of the given array. In this case, red_band
is a integer array (specifically uint16
). Attempting to populate an integer array with a floating point number like 0.5
results in truncation, hence why L
contains all 0
s.
To create a float array with the same size as red_band
, you can use np.full
instead:
L = np.full(red_band.shape, 0.5)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论