Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Return the cumulative product treating NaNs as one but change the type of result in Python
To return the cumulative product of array elements over a given axis treating NaNs as one, use the nancumprod() method. The cumulative product does not change when NaNs are encountered and leading NaNs are replaced by ones. Ones are returned for slices that are all-NaN or empty.
The method returns a new array holding the result unless out is specified. Cumulative works like: 5, 5*10, 5*10*15, 5*10*15*20. The dtype parameter allows you to change the type of the returned array from the original array's data type.
Syntax
numpy.nancumprod(a, axis=None, dtype=None, out=None)
Parameters
a: Input array
axis: Axis along which the cumulative product is computed. By default the input is flattened
dtype: Type of the returned array and accumulator. If not specified, defaults to the dtype of a
out: Alternative output array in which to place the result
Example
Let's create an array with NaN values and calculate the cumulative product ?
import numpy as np
# Creating a numpy array with NaN values
arr = np.array([[5, 10, 15], [20, np.nan, 30]])
# Display the array
print("Original Array:")
print(arr)
# Check the original datatype
print("\nOriginal datatype:", arr.dtype)
# Calculate cumulative product treating NaNs as 1, changing dtype to int
result = np.nancumprod(arr, axis=1, dtype=int)
print("\nCumulative Product (dtype=int):")
print(result)
print("Result datatype:", result.dtype)
Original Array: [[ 5. 10. 15.] [20. nan 30.]] Original datatype: float64 Cumulative Product (dtype=int): [[ 5 50 750] [20 20 600]] Result datatype: int32
How It Works
In the above example:
- Row 1: [5, 10, 15] ? [5, 5*10=50, 50*15=750]
- Row 2: [20, NaN, 30] ? [20, 20*1=20, 20*30=600] (NaN treated as 1)
Different Data Types
You can specify different data types for the result ?
import numpy as np
arr = np.array([2.5, 4.0, np.nan, 6.0])
# Default dtype (float)
result_default = np.nancumprod(arr)
print("Default dtype:", result_default.dtype)
print("Result:", result_default)
# Convert to integer
result_int = np.nancumprod(arr, dtype=int)
print("\nInteger dtype:", result_int.dtype)
print("Result:", result_int)
# Convert to complex
result_complex = np.nancumprod(arr, dtype=complex)
print("\nComplex dtype:", result_complex.dtype)
print("Result:", result_complex)
Default dtype: float64 Result: [ 2.5 10. 10. 60. ] Integer dtype: int32 Result: [ 2 10 10 60] Complex dtype: complex128 Result: [ 2.5+0.j 10. +0.j 10. +0.j 60. +0.j]
Conclusion
The nancumprod() method treats NaN values as 1 during cumulative product calculation. Use the dtype parameter to control the data type of the returned array, which is useful for memory optimization or specific numerical requirements.
