在Python中,返回沿轴0的数组元素的累积积,并将NaN视为1
要返回沿给定轴的数组元素的累积积,并将NaN视为1,请使用`nancumprod()`方法。当遇到NaN时,累积积不会改变,并且前导NaN将被替换为1。对于全是NaN或为空的切片,将返回1。该方法返回一个包含结果的新数组,除非指定了`out`参数,在这种情况下,结果将返回到`out`参数中。
该方法的工作方式如下:5, 5*10, 5*10*15, 5*10*15*20。第一个参数是输入数组。第二个参数是计算累积积的轴。默认情况下,输入被展平。
第三个参数是返回数组的类型,以及用于相乘元素的累加器的类型。如果未指定`dtype`,则默认为`a`的`dtype`,除非`a`具有精度低于默认平台整数的整数`dtype`。在这种情况下,将改为使用默认平台整数。第四个参数是用于放置结果的备用输出数组。它必须与预期输出具有相同的形状和缓冲区长度,但结果值的类型将根据需要进行转换。
步骤
首先,导入所需的库:
import numpy as np
使用`array()`方法创建一个NumPy数组。我们添加了包含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。对于全是NaN或为空的切片,将返回1。该方法返回一个包含结果的新数组,除非指定了`out`参数,在这种情况下,结果将返回到`out`参数中。
print("\nCumulative Product of array elements...\n",np.nancumprod(arr, axis = 0))
示例
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
print("\nCumulative Product of array elements...\n",np.nancumprod(arr, axis = 0))输出
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. 10. 15.] [100. 10. 450.]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP