返回数组元素在轴0上的累积乘积,在Python中把NaN视为1
在这篇文章中,我们将讨论如何用Python和NumPy找到负的输入值被提高到什么程度的结果。
示例
输入: [[10. nan][nan 20.]]
输出: [ 10. 10. 10. 200.]
解释: 在一个给定的轴上,数组元素的累积乘积。
NumPy.nancumprod 方法
numpy nancumprod()用于返回数组元素在0轴上的累积乘积,将NaN视为’1’。该方法返回沿给定轴的数组元素的总和,NaNs被视为1。当发现NaNs并将领先的NaNs替换成1时,累积乘积保持不变。对于全NaN或空片,会返回1。
语法: numpy.nancumprod(a, axis=None, dtype=None)
参数:
- a: 输入阵列。
- axis: int value, optional.0或1。
- dtype: 可选值。 返回数组的类型,以及累加器的类型。
返回:数组元素的累积乘积。
示例 1 :
在这个例子中,我们导入了NumPy包,使用np.array()方法创建了一个数组。关于数组的信息,如形状、数据类型和尺寸,可以通过.shape , .dtype , 和 .ndim属性找到。 nancumprod()用于返回数组元素的累积乘积。这里的轴是无。
# import packages
import numpy as np
# Creating an array with integers and nans
array = np.array([[10,np.nan],[np.nan,20]])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# cumulative product of array elements
print(np.nancumprod(array))
输出:
[[10. nan]
[nan 20.]]
Shape of the array is : (2, 2)
The dimension of the array is : 2
Datatype of our Array is : float64
[ 10. 10. 10. 200.]
示例 2:
在这个例子中,我们通过在轴参数中传递0来返回数组元素沿行的累积乘积。
# import packages
import numpy as np
# Creating an array with integers and nans
array = np.array([[10,np.nan],[np.nan,20]])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# cumulative product of array elements along axis =0 (along rows)
print(np.nancumprod(array,axis=0))
输出:
[10. nan]
[nan 20.]]
Shape of the array is : (2, 2)
The dimension of the array is : 2
Datatype of our Array is : float64
[[10. 1.]
[10. 20.]]
示例 3:
在这个例子中,我们通过在轴参数中传递1来返回数组元素与列的累积乘积。
# import packages
import numpy as np
# Creating an array with integers and nans
array = np.array([[10,np.nan],[np.nan,20]])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# cumulative product of array elements along
# axis =1(along columns)
print(np.nancumprod(array,axis=1))
输出:
[[10. nan]
[nan 20.]]
Shape of the array is : (2, 2)
The dimension of the array is : 2
Datatype of our Array is : float64
[[10. 10.]
[ 1. 20.]]