在 Numpy 中降低陣列維度並使用不同的值初始化降維
要將陣列的維度降低一個維度,請在 Python Numpy 中使用 **np.ufunc.reduce()** 方法。在這裡,我們使用了 **add.reduce()** 將其簡化為所有元素的總和。要使用不同的值初始化降維,請使用“initials”引數。
通用函式(簡稱 ufunc)是在元素級對 ndarray 進行運算的函式,支援陣列廣播、型別轉換以及其他一些標準功能。也就是說,ufunc 是對一個函式的“向量化”包裝,該函式需要固定數量的特定輸入併產生固定數量的特定輸出。
步驟
首先,匯入所需的庫 -
import numpy as np
建立一個一維陣列 -
arr = np.array([7, 14, 21, 28, 35])
顯示陣列 -
print("Array...
", arr)獲取陣列的型別 -
print("
Our Array type...
", arr.dtype)
獲取陣列的維度 -
print("
Our Array Dimensions...
",arr.ndim)要將陣列的維度降低一個維度,請在 Python Numpy 中使用 np.ufunc.reduce() 方法。在這裡,我們使用了 add.reduce() 將其簡化為所有元素的總和。要使用不同的值初始化降維,請使用“initials”引數 -
print("
Result (addition)...
",np.add.reduce(arr, initial = 99))
示例
import numpy as np
# The numpy.ufunc has functions that operate element by element on whole arrays.
# ufuncs are written in C (for speed) and linked into Python with NumPy’s ufunc facility
# Create a 1D array
arr = np.array([7, 14, 21, 28, 35])
# Display the array
print("Array...
", arr)
# Get the type of the array
print("
Our Array type...
", arr.dtype)
# Get the dimensions of the Array
print("
Our Array Dimensions...
",arr.ndim)
# To reduce array’s dimension by one, use the np.ufunc.reduce() method in Python Numpy
# Here, we have used add.reduce() to reduce it to the addition of all the elements
# To initialize the reduction with a different value, use the "initials" parameter
print("
Result (addition)...
",np.add.reduce(arr, initial = 99))輸出
Array... [ 7 14 21 28 35] Our Array type... int64 Our Array Dimensions... 1 Result (addition)... 204
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP