在 Python 中返回累积积,将 NaN 视为 1,并更改结果的类型


要返回数组元素在给定轴上的累积积,并将 NaN 视为 1,请使用 nancumprod() 方法。当遇到 NaN 时,累积积不会发生变化,并且前导 NaN 会被替换为 1。对于全是 NaN 或为空的切片,将返回 1。

除非指定了 out,否则该方法返回一个包含结果的新数组,在这种情况下,将返回该数组。累积的工作方式如下:5、5*10、5*10*15、5*10*15*20。第一个参数是输入数组。第二个参数是计算累积积的轴。默认情况下,输入被展平。

第三个参数是返回数组的类型,以及用于乘法元素的累加器的类型。如果未指定 dtype,则默认为 a 的 dtype,除非 a 的整数 dtype 的精度小于默认平台整数的精度。在这种情况下,将改用默认平台整数。

第四个参数是用于放置结果的备用输出数组。它必须与预期输出具有相同的形状和缓冲区长度,但如果需要,结果值的类型将被转换。

步骤

首先,导入所需的库 -

import numpy as np

使用 array() 方法创建一个 numpy 数组。我们添加了带有 nan 的 int 类型的元素 -

arr = np.array([[5, 10, 15], [20, np.nan, 30]])

显示数组 -

print("Our Array...\n",arr)

检查维度 -

print("\nDimensions of our Array...\n",arr.ndim)

获取数据类型 -

print("\nDatatype of our Array object...\n",arr.dtype)

要返回数组元素在给定轴上的累积积,并将 NaN 视为 1,请使用 nancumprod() 方法,当遇到 NaN 时,累积积不会发生变化,并且前导 NaN 会被替换为 1 -

print("\nCumulative Product of array elements...\n",np.nancumprod(arr, axis = 1, dtype = int))

示例

Open Compiler
import numpy as np # Creating a numpy array using the array() method # We have added elements of int type with nan arr = np.array([[5, 10, 15], [20, np.nan, 30]]) # Display the array print("Our Array...\n",arr) # Check the Dimensions print("\nDimensions of our Array...\n",arr.ndim) # Get the Datatype print("\nDatatype of our Array object...\n",arr.dtype) # To return the cumulative product of array elements over a given axis treating NaNs as one, use the nancumprod() method # The cumulative product does not change when NaNs are encountered and leading NaNs are replaced by ones. print("\nCumulative Product of array elements...\n",np.nancumprod(arr, axis = 1, dtype = int))

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

Our Array...
[[ 5. 10. 15.]
[20. nan 30.]]

Dimensions of our Array...
2

Datatype of our Array object...
float64

Cumulative Product of array elements...
[[ 5 50 750]
[ 20 20 600]]

更新于: 2022-03-02

96 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告