返回Python中将NaN视为1的轴向上数组元素的累积乘积
要返回将NaN视为1并在给定轴向上计算数组元素的累积乘积,请使用nancumprod()方法。遇到NaN时,累积乘积不会更改,并且前导的NaN将被替换为1。对于全部为NaN或为空的切片,将返回1。该方法返回一个新的数组来保存结果,除非指定了out参数,否则将返回该数组。
累积计算的过程类似于,5,510,51015,5101520。第一个参数是输入数组。第二个参数是计算累积乘积的轴。默认情况下输入数组会被展平。第三个参数是返回数组的类型,以及累计乘积使用的累加器的类型。如果未指定dtype,则默认为输入数组的dtype,除非输入数组具有精度小于默认平台整数的整数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.]]
极客笔记