在Python中,返回沿轴1累积数组元素的乘积,将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数组。我们添加了int类型的元素和nan:
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()方法:
print("\nCumulative Product of array elements...\n",np.nancumprod(arr, axis = 1))
示例
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))
输出
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.]]
广告