在NumPy数组中求和十进制数。

huangapple go评论76阅读模式
英文:

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 0s.

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)

huangapple
  • 本文由 发表于 2023年1月6日 10:50:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/75026472.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定