在 Python 中返回数组元素的累积和,将 NaN 视为零
要返回在给定轴上数组元素的累积和,并将 NaN 视为零,请使用 nancumprod() 方法。当遇到 NaN 时,累积和不会改变,并且前导 NaN 将被零替换。对于全是 NaN 或为空的切片,将返回零。
除非指定了 out,否则该方法将返回一个包含结果的新数组。结果与 a 的大小相同,如果 axis 不为 None 或 a 是一个一维数组,则结果与 a 的形状相同。累积的工作方式如下:5, 5+10, 5+10+15, 5+10+15+20。第一个参数是输入数组。第二个参数是计算累积和的轴。默认值 (None) 是在扁平化数组上计算累积和。
第三个参数是返回数组的类型以及用于对元素求和的累加器的类型。如果未指定 dtype,则默认为 a 的 dtype,除非 a 的整数 dtype 的精度小于默认平台整数的精度。在这种情况下,将使用默认平台整数。第四个参数是用于放置结果的备用输出数组。它必须与预期输出具有相同的形状和缓冲区长度,但如有必要,类型将被转换。
步骤
首先,导入所需的库:
import numpy as np
使用 array() 方法创建一个 NumPy 数组。我们添加了包含 nan 的 int 类型元素:
arr = np.array([10, 20, 30, 40, np.nan])
显示数组:
print("Our Array...\n",arr)检查维度:
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型:
print("\nDatatype of our Array object...\n",arr.dtype)要返回在给定轴上数组元素的累积和,并将 NaN 视为零,请使用 nancumprod() 方法。当遇到 NaN 时,累积和不会改变,并且前导 NaN 将被零替换。对于全是 NaN 或为空的切片,将返回零:
print("\nCumulative Sum of array elements...\n",np.nancumsum(arr))示例
import numpy as np
# Creating a numpy array using the array() method
# We have added elements of int type with nan
arr = np.array([10, 20, 30, 40, np.nan])
# 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 sum of array elements over a given axis treating NaNs as zero, use the nancumprod() method
# The cumulative sum does not change when NaNs are encountered and leading NaNs are replaced by zeros.
print("\nCumulative Sum of array elements...\n",np.nancumsum(arr))输出
Our Array... [10. 20. 30. 40. nan] Dimensions of our Array... 1 Datatype of our Array object... float64 Cumulative Sum of array elements... [ 10. 30. 60. 100. 100.]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP