Return the cumulative product of array elements over axis 0 treating NaNs as one in Python
Last Updated :
22 Apr, 2022
In this article, we will discuss how to find the result of the power to which the negative input value is raised with Python and NumPy.
Example
Input: [[10. nan][nan 20.]]
Output: [ 10. 10. 10. 200.]
Explanation: The cumulative product of array elements over a given axis.
NumPy.nancumprod method
The numpy nancumprod() is used to return the cumulative product of array elements over axis 0 by treating NaNs as ‘1’. This method returns the sum of array elements along a given axis, with NaNs considered as one. When NaNs are found and leading NaNs are replaced with ones, the cumulative product remains unchanged. For all-NaN or empty slices, ones are returned.
Syntax: numpy.nancumprod(a, axis=None, dtype=None)
Parameters:
- a: input array.
- axis: int value, optional. 0 or 1.
- dtype: optional value. The returning array’s type, as well as the accumulator.
Returns: The cumulative product of array elements.
Example 1 :
In this example, we are importing the NumPy package and an array is created using the np.array() method. Information about the array such as shape, datatype, and dimension can be found using the .shape, .dtype, and .ndim attributes. nancumprod() is used to return the cumulative product of array elements. here axis is None.
Python3
import numpy as np
array = np.array([[ 10 ,np.nan],[np.nan, 20 ]])
print (array)
print ( "Shape of the array is : " ,array.shape)
print ( "The dimension of the array is : " ,array.ndim)
print ( "Datatype of our Array is : " ,array.dtype)
print (np.nancumprod(array))
|
Output:
[[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.]
Example 2:
In this example, we return the cumulative product of array elements along rows by passing 0 in the axis parameter.
Python3
import numpy as np
array = np.array([[ 10 ,np.nan],[np.nan, 20 ]])
print (array)
print ( "Shape of the array is : " ,array.shape)
print ( "The dimension of the array is : " ,array.ndim)
print ( "Datatype of our Array is : " ,array.dtype)
print (np.nancumprod(array,axis = 0 ))
|
Output:
[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.]]
Example 3:
In this example, we return the cumulative product of array elements along with columns by passing 1 in the axis parameter.
Python3
import numpy as np
array = np.array([[ 10 ,np.nan],[np.nan, 20 ]])
print (array)
print ( "Shape of the array is : " ,array.shape)
print ( "The dimension of the array is : " ,array.ndim)
print ( "Datatype of our Array is : " ,array.dtype)
print (np.nancumprod(array,axis = 1 ))
|
Output:
[[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.]]
Share your thoughts in the comments
Please Login to comment...