在Python中使用切片更改多个Numpy数组元素 [英] Changing multiple Numpy array elements using slicing in Python
本文介绍了在Python中使用切片更改多个Numpy数组元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
说我有 numpy
数组 arr_1 = np.arange(10)
返回:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
如何使用切片将多个元素更改为某个值?
How do I change multiple elements to a certain value using slicing?
例如:将从第一个元素开始的每五个元素中出现的第零个,第一个和第二个元素更改为100.我想要这样做:
For example: changing the zeroth, first and second element that occur every five elements, starting from the first element, to 100. I want this:
array([0, 100, 100, 100, 4, 5, 100, 100, 100, 9])
我尝试了 arr_1 [1 :: [5,6,7]] = 100
,但这不起作用.
I tried arr_1[1::[5, 6, 7]] = 100
but that doesn't work.
推荐答案
这是使用使用原始样品运行样品-
Sample run with original sample -
In [849]: a = np.arange(10) # Input array
...: idx = np.array([0,1,2]) # Indices to be set
...: offset = 1 # Offset
...:
...: a[np.in1d(np.mod(np.arange(a.size),5) , idx+offset)] = 100
...:
In [850]: a
Out[850]: array([ 0, 100, 100, 100, 4, 5, 100, 100, 100, 9])
使用非顺序索引
-
In [851]: a = np.arange(11) # Input array
...: idx = np.array([0,2,3]) # Indices to be set
...: offset = 1 # Offset
...:
In [852]: a[np.in1d(np.mod(np.arange(a.size),5) , idx+offset)] = 100
In [853]: a
Out[853]: array([ 0, 100, 2, 100, 100, 5, 100, 7, 100, 100, 10])
这篇关于在Python中使用切片更改多个Numpy数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文