在Python中,返回沿軸0的陣列元素的累積積,並將NaN視為1


要返回沿給定軸的陣列元素的累積積,並將NaN視為1,請使用`nancumprod()`方法。當遇到NaN時,累積積不會改變,並且前導NaN將被替換為1。對於全是NaN或為空的切片,將返回1。該方法返回一個包含結果的新陣列,除非指定了`out`引數,在這種情況下,結果將返回到`out`引數中。

該方法的工作方式如下:5, 5*10, 5*10*15, 5*10*15*20。第一個引數是輸入陣列。第二個引數是計算累積積的軸。預設情況下,輸入被展平。

第三個引數是返回陣列的型別,以及用於相乘元素的累加器的型別。如果未指定`dtype`,則預設為`a`的`dtype`,除非`a`具有精度低於預設平臺整數的整數`dtype`。在這種情況下,將改為使用預設平臺整數。第四個引數是用於放置結果的備用輸出陣列。它必須與預期輸出具有相同的形狀和緩衝區長度,但結果值的型別將根據需要進行轉換。

步驟

首先,匯入所需的庫:

import numpy as np

使用`array()`方法建立一個NumPy陣列。我們添加了包含NaN的整數型別元素:

arr = np.array([[5, 10, 15], [20, np.nan, 30]])

顯示陣列:

print("Our Array...\n",arr)

檢查維度:

print("\nDimensions of our Array...\n",arr.ndim)

獲取資料型別:

print("\nDatatype of our Array object...\n",arr.dtype)

要返回沿給定軸的陣列元素的累積積,並將NaN視為1,請使用`nancumprod()`方法。當遇到NaN時,累積積不會改變,並且前導NaN將被替換為1。對於全是NaN或為空的切片,將返回1。該方法返回一個包含結果的新陣列,除非指定了`out`引數,在這種情況下,結果將返回到`out`引數中。

print("\nCumulative Product of array elements...\n",np.nancumprod(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([[5, 10, 15], [20, np.nan, 30]])

# 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 product of array elements over a given axis treating NaNs as one, use the nancumprod() method
print("\nCumulative Product of array elements...\n",np.nancumprod(arr, axis = 0))

輸出

Our Array...
[[ 5. 10. 15.]
[20. nan 30.]]

Dimensions of our Array...
2

Datatype of our Array object...
float64

Cumulative Product of array elements...
[[ 5. 10. 15.]
[100. 10. 450.]]

更新於:2022年3月2日

瀏覽量:115

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.