在Python中将给定轴上数组元素的累积乘积视为NaN的基础上返回
要返回将NaN视为一个的给定轴上数组元素的累积乘积,请使用nancumprod()方法。当遇到NaN时,累积乘积不会改变,并且前导NaN将被替换为1。对于全为NaN或空的切片,会返回1。除非指定了out参数,否则该方法会返回一个包含结果的新数组。
累积乘法的运算方式为:5,510,51015,5101520。第一个参数是输入数组,第二个参数是计算累积乘积的轴。默认情况下,输入会被展平。第三个参数是返回数组的类型,以及元素相乘的累加器的类型。如果未指定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()方法。当遇到NaN时,累积乘积不会发生变化,并且前导的NaN将被替换为1。
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.]]