在 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