numpy中的put,putmask, place的用法

np.put(a, ind, v, mode=‘raise’)

参数解释:
Parameters:
a : ndarray
Target array.

ind : array_like
Target indices, interpreted as integers.

v : array_like
Values to place in a at target indices. If v is shorter than ind it will be repeated as necessary.

mode : {‘raise’, ‘wrap’, ‘clip’}, optional
Specifies how out-of-bounds indices will behave.

‘raise’ – raise an error (default)
‘wrap’ – wrap around
‘clip’ – clip to the range
‘clip’ mode means that all indices that are too large are replaced by the index that addresses the last element along that axis. Note that this disables indexing with negative numbers. In ‘raise’ mode, if an exception occurs the target array may still be modified.(“clip”模式意味着所有太大的索引都将替换为沿该轴寻址最后一个元素的索引。)

表示对数组中指定的索引值指向的元素替换成指定的值。索引在扁平的目标数组上工作
例子:

a = np.array([0,5,6,75,6])
np.put(a, [0, 2], [-44, -55])
a

结果
array([-44, 5, -55, 75, 6])

a = np.arange(5)
np.put(a, 22, -5, mode='clip')
a

结果:
array([ 0, 1, 2, 3, -5])
注意这里指定的索引值22,超过了数组的索引值,这样就是直接将最后一个数替换成指定的数

np.putmask()

numpy.putmask(a, mask, values)¶
参数解释:
Parameters:
a : array_like
Target array.

mask : array_like
Boolean mask array. It has to be the same shape as a.

values : array_like
Values to put into a where mask is True. If values is smaller than a it will be repeated.
例子:

x = np.arange(6).reshape(2, 3)
np.putmask(x, x>2, x**2)
x

结果:
array([[ 0, 1, 2],
[ 9, 16, 25]])
解释:就是将数组a中的满足条件大于2的值做平方操作
当给出的values值额个数小于满足条件的数组中的值得个数时,需要将给定的值重复
例子:

x = np.arange(5)
np.putmask(x, x>1, [-33, -44])
x

结果如下:
array([ 0, 1, -33, -44, -33])
解释:在这里满足大于1的值得个数超过了2个 ,在进行值的替换的过程中就主要是对这一values进行重复

np.place()

numpy.place(arr, mask, vals)[source]¶
根据条件值和输入值更改数组元素。
与np.copyto(arr,vals,其中=mask)类似,不同之处在于place使用vals的前n个元素,其中n是mask中的真值数,而copyto使用mask为真的元素。
请注意,提取的位置正好相反。

Parameters:
arr : ndarray
Array to put data into.

mask : array_like
Boolean mask array. Must have the same size as a.

vals : 1-D sequence
Values to put into a. Only the first N elements are used, where N is the number of True values in mask. If vals is smaller than N, it will be repeated, and if elements of a are to be masked, this sequence must be non-empty.
例子:

arr = np.arange(6).reshape(2, 3)
np.place(arr, arr>2, [44, 55])
arr

结果如下:
array([[ 0, 1, 2],
[44, 55, 44]])
解释:将arr中满足值大于2的元素用给定的值进行替换,出现给定的值的个数与满足条件的个数不同时,就相当于把values值进行重复操作

numpy.copyto¶

numpy.copyto(dst, src, casting=‘same_kind’, where=True)
表示讲一个数组的值复制到另外一个数组
例子:

a=np.arange(4).reshape(2,2)
b=np.array([5,3,8,2]).reshape(2,2)
print(a)
print(b)
print('***')
np.copyto(a,b)
print(a)
print(b)

结果如下:
[[0 1]
[2 3]]
[[5 3]
[8 2]]


[[5 3]
[8 2]]
[[5 3]
[8 2]]

猜你喜欢

转载自blog.csdn.net/weixin_43213268/article/details/88926626