在 NumPy 中對由“indices”指定的元素執行運算元的非緩衝就地操作
要在 Python NumPy 中對由“indices”指定的元素執行運算元的非緩衝就地操作,請使用 **numpy.ufunc.at()** 方法。
**numpy.ufunc** 包含逐元素對整個陣列進行操作的函式。ufunc是用C語言編寫的(為了速度),並透過NumPy的ufunc功能連結到Python。通用函式(或簡稱ufunc)是在元素級對ndarray進行操作的函式,支援陣列廣播、型別轉換和許多其他標準特性。也就是說,ufunc是“向量化”的函式包裝器,它接受固定數量的特定輸入併產生固定數量的特定輸出。
步驟
首先,匯入所需的庫 -
import numpy as np
建立兩個一維陣列 -
arr1 = np.array([10, 20, 30, 40, 50]) arr2 = np.array([15, 25, 35, 45, 55])
顯示陣列 -
print("Array 1...
", arr1)
print("
Array 2...
", arr2)獲取陣列的型別 -
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)獲取陣列的維度 -
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)要在 Python NumPy 中對由“indices”指定的元素執行運算元的非緩衝就地操作,請使用 numpy.ufunc.at() 方法。
設定負值。np.negative.at() 用於將特定專案設定為負值。這裡,第二個引數是索引,即用於索引第一個運算元的陣列狀索引物件或切片物件。如果第一個運算元具有多個維度,則索引可以是陣列狀索引物件或切片物件的元組。
np.negative.at(arr1, [0, 1])
print("
Set negative values...
", arr1)設定正值。np.add.at() 用於將特定專案設定為增量值 -
np.add.at(arr2, [0, 1], 1)
print("
Set positive values...
", arr2)示例
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 two 1d arrays
arr1 = np.array([10, 20, 30, 40, 50])
arr2 = np.array([15, 25, 35, 45, 55])
# Display the arrays
print("Array 1...
", arr1)
print("
Array 2...
", arr2)
# Get the type of the arrays
print("
Our Array 1 type...
", arr1.dtype)
print("
Our Array 2 type...
", arr2.dtype)
# Get the dimensions of the Arrays
print("
Our Array 1 Dimensions...
",arr1.ndim)
print("
Our Array 2 Dimensions...
",arr2.ndim)
# To perform unbuffered in place operation on operand for elements specified by ‘indices, use the numpy.ufunc.at() method in Python Numpy
# Set negative values
# The np.negative.at() is used to set specific items to negative values
# Here, the 2nd parameter are indices i.e. Array like index object or slice object for indexing into
# first operand. If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects.
np.negative.at(arr1, [0, 1])
print("
Set negative values...
", arr1)
# Set positive values
# The np.add.at() is used to set specific items to increment values
np.add.at(arr2, [0, 1], 1)
print("
Set positive values...
", arr2)輸出
Array 1... [10 20 30 40 50] Array 2... [15 25 35 45 55] Our Array 1 type... int64 Our Array 2 type... int64 Our Array 1 Dimensions... 1 Our Array 2 Dimensions... 1 Set negative values... [-10 -20 30 40 50] Set positive values... [16 26 35 45 55]
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP