返回陣列元素的累積和,將NaN視為零,但更改Python中的結果型別


要返回在給定軸上對陣列元素的累積和,並將NaN視為零,請使用nancumprod()方法。當遇到NaN時,累積和不會改變,前導NaN將被零替換。對於全是NaN或空的切片,將返回零。

第一個引數是輸入陣列。第二個引數是計算累積和的軸。預設值(None)是在展平的陣列上計算累積和。第三個引數是返回陣列和累加器的型別,在其中對元素求和。如果未指定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()方法。當遇到NaN時,累積和不會改變,前導NaN將被零替換:

print("\nCumulative Sum of array elements...\n",np.nancumsum(arr, axis = 1, dtype = int))

示例

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

print("\nCumulative Sum of array elements...\n",np.nancumsum(arr, axis = 1, dtype = int))

輸出

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 30 60]
[ 40 40 100]]

更新於:2022年2月28日

104 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.