在 Python 中返回数组元素在给定轴 0 上的累积和,将 NaN 视为零
要返回数组元素在给定轴上累积和,并将 NaN 视为零,请使用 nancumprod() 方法。当遇到 NaN 时,累积和不会改变,并且前导 NaN 将被零替换。对于全 NaN 或空切片,将返回零。累积的工作方式如下:5、5+10、5+10+15、5+10+15+20。
第一个参数是输入数组。第二个参数是计算累积和的轴。默认值(None)是在展平的数组上计算 cumsum。第三个参数是返回数组和累加器中元素求和的类型的类型。如果未指定 dtype,则默认为 a 的 dtype,除非 a 的整数 dtype 的精度低于默认平台整数的精度。在这种情况下,将使用默认平台整数。第四个参数是要放置结果的备用输出数组。它必须与预期输出具有相同的形状和缓冲区长度,但如果需要,类型将被强制转换。
步骤
首先,导入所需的库 -
import numpy as np
使用 array() 方法创建一个 NumPy 数组。我们添加了带有 nan 的 int 类型的元素 -
arr = np.array([[10, 20, 30], [40, np.nan, 60]])
显示数组 -
print("Our Array...\n",arr)检查维度 -
print("\nDimensions of our Array...\n",arr.ndim)
获取数据类型 -
print("\nDatatype of our Array object...\n",arr.dtype)要返回数组元素在给定轴上累积和,并将 NaN 视为零,请使用 nancumprod() 方法 -
print("\nCumulative Sum of array elements...\n",np.nancumsum(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([[10, 20, 30], [40, np.nan, 60]])
# 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.
# Zeros are returned for slices that are all-NaN or empty.
print("\nCumulative Sum of array elements...\n",np.nancumsum(arr, axis = 0))输出
Our Array... [[10. 20. 30.] [40. nan 60.]] Dimensions of our Array... 2 Datatype of our Array object... float64 Cumulative Sum of array elements... [[10. 20. 30.] [50. 20. 90.]]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP