简体   繁体   English

用n替换numpy数组中的多个元素

[英]Replace multiple elements in numpy array with 1

In a given numpy array X : 在给定的numpy数组X

X = array([1,2,3,4,5,6,7,8,9,10])

I would like to replace indices (2, 3) and (7, 8) with a single element -1 respectively, like: 我想分别用单个元素-1替换索引(2, 3)(7, 8) ,如:

X = array([1,2,-1,5,6,7,-1,10])

In other words, I replaced values at indices (2, 3) and (7,8) of the original array with a singular value. 换句话说,我用原始值替换原始数组的索引(2, 3)(7,8)处的值。

Question is: Is there a numpy-ish way (ie without for loops and usage of python lists) around it? 问题是:它周围是否有一种numpy-ish方式(即没有for循环和使用python列表)? Thanks. 谢谢。

Note: This is NOT equivalent of replacing a single element in-place with another. 注意:这不等于用另一个元素就地替换单个元素。 Its about replacing multiple values with a "singular" value. 它用“奇异”值替换多个值。 Thanks. 谢谢。

A solution using numpy.delete , similar to @pault, but more efficient as it uses pure numpy indexing. 使用numpy.delete的解决方案,类似于@pault,但更高效,因为它使用纯粹的numpy索引。 However, because of this efficient indexing, it means that you cannot pass jagged arrays as indices 但是,由于这种有效的索引,这意味着您不能将锯齿状数组作为索引传递

Setup 设定

a = np.array([1,2,3,4,5,6,7,8,9,10])
idx = np.stack([[2, 3], [7, 8]])

a[idx] = -1
np.delete(a, idx[:, 1:])

array([ 1,  2, -1,  5,  6,  7, -1, 10])

I'm not sure if this can be done in one step, but here's a way using np.delete : 我不确定这是否可以一步完成,但这是使用np.delete的方法:

import numpy as np
from operator import itemgetter

X = np.array(range(1,11))
to_replace = [[2,3], [7,8]]


X[list(map(itemgetter(0), to_replace))] = -1
X = np.delete(X, list(map(lambda x: x[1:], to_replace)))
print(X)
#[ 1  2 -1  5  6  7 -1 10]

First we replace the first element of each pair with -1 . 首先,我们用-1替换每对中的第一个元素。 Then we delete the remaining elements. 然后我们删除剩余的元素。

Try np.put : 试试np.put

np.put(X, [2,3,7,8], [-1,0]) # `0` can be changed to anything that's not in the array
print(X[X!=0]) # whatever You put as an number in `put`

So basically use put to do the values for the indexes, then drop the zero-values. 所以基本上使用put来做索引的值,然后删除零值。

Or as @khan says, can do something that's out of range: 或者像@khan所说,可以做一些超出范围的事情:

np.put(X, [2,3,7,8], [-1,np.max(X)+1])
print(X[X!=X.max()])

All Output: 所有输出:

[ 1  2 -1  5  6  7 -1 10]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM