我如何替换ndarray中的每n个实例?

问题描述 投票:1回答:1

我有一个如下的numpy数组atoms.numbers


array([27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57, 57, 57, 57, 27, 27,  8,
        8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
        8,  8,  8,  8,  8,  8, 27, 27, 27, 27, 27, 27, 57, 57, 57, 57, 57,
       57, 57, 57, 27, 27,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8])

我可以使用以下命令替换所有相同的实例,例如数组中的每个“ 57”:

atoms.numbers[atoms.numbers==57]=38

给出:

array([27, 27, 27, 27, 27, 27, 38, 38, 38, 38, 38, 38, 38, 38, 27, 27,  8,
        8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,
        8,  8,  8,  8,  8,  8, 27, 27, 27, 27, 27, 27, 38, 38, 38, 38, 38,
       38, 38, 38, 27, 27,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8,  8])

我希望能够替换数组中的每个第n个实例。我尝试过:

n=5
atoms.numbers[atoms.numbers==57][::n]=38

这不起作用。

python-3.x scipy instance numpy-ndarray numpy-slicing
1个回答
0
投票

使用np.where查找感兴趣项目的索引。查找每个第n个索引。更新项目:

locations = np.where(numbers == 57)[0]
numbers[locations[::n]] = 38
© www.soinside.com 2019 - 2024. All rights reserved.