以最pythonian方式编写ndarray的sub-ndarray.的Python 2 [英] Writting in sub-ndarray of a ndarray in the most pythonian way. Python 2
问题描述
我有一个像这样的ndarray:
I have a ndarray like this one:
number_of_rows = 3
number_of_columns = 3
a = np.arange(number_of_rows*number_of_columns).reshape(number_of_rows,number_of_columns)
a
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
但是我想要这样的东西:
But I want something like this:
array([[0, 100, 101],
[3, 102, 103],
[6, 7, 8]])
要做到这一点,我想避免一一做,我宁愿在数组或矩阵中做,因为以后我想扩展代码. 不,我已经更改了初始矩阵的子矩阵(在数学上,就本例ndarray而言).在示例中,考虑的列为[1,2],行为[0,1].
To do that I want to avoid to do it one by one, I rather prefer to do it in arrays or matrices, because later I want to extend the code. Nothe I have change a submatrix of the initial matrix (in mathematical terms, in terms of this example ndarray). In the example the columns considered are [1,2] and the rows [0,1].
columns_to_keep = [1,2]
rows_to_keep = [0,1]
我的第一次尝试是做
a[rows_to_keep,:][:,columns_to_keep] = np.asarray([[100,101],[102,103]])
但是这个不会修改首字母a,我没有任何错误,所以a =
array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]])
所以我实现了一段代码来完成这项工作:
So I have implemented a piece of code that goes do the job:
b = [[100, 101],[102, 103]]
for i in range(len(rows_to_keep)):
a[i,columns_to_keep] = b[i]
我以为前几行做的很好,我想知道如何以更快的速度进行切片.也可以通过以下方式实现:
Al thought the previous lines do the job I am wondering how to do it slicing and in a faster fashion. Also in a way that with:
columns_to_keep = [0,2]
rows_to_keep = [0,2]
所需的输出是
array([[100, 1, 101],
[3, 4, 5],
[102, 7, 103]]).
非常感谢!
推荐答案
使用像[1,2]
这样的列表进行索引称为高级索引.它本身会产生一个副本,而不是视图.您必须使用一个索引表达式,而不是两个索引表达式来分配或更改值.即a[[1,2],:]
是副本,a[[1,2],:][:,[1,2]] += 100
修改该副本,而不是原始的a
.
Indexing with lists like [1,2]
is called advanced indexing. By itself it produces a copy, not a view. You have to use one indexing expression, not two to assign or change values. That is a[[1,2],:]
is a copy, a[[1,2],:][:,[1,2]] += 100
modifies that copy, not the original a
.
In [68]: arr = np.arange(12).reshape(3,4)
使用切片索引;这是基本的索引编制:
Indexing with slices; this is basic indexing:
In [69]: arr[1:,2:]
Out[69]:
array([[ 6, 7],
[10, 11]])
In [70]: arr[1:,2:] += 100
In [71]: arr
Out[71]:
array([[ 0, 1, 2, 3],
[ 4, 5, 106, 107],
[ 8, 9, 110, 111]])
对列表进行相同的索引编制需要相互广播"的数组. ix_
是生成这些的便捷方法:
Doing the same indexing with lists requires arrays that 'broadcast' against each other. ix_
is a handy way of generating these:
In [73]: arr[np.ix_([1,2],[2,3])]
Out[73]:
array([[106, 107],
[110, 111]])
In [74]: arr[np.ix_([1,2],[2,3])] -= 100
In [75]: arr
Out[75]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
这是ix_
生成的-一个数组元组,一个数组的形状为(2,1),另一个数组的形状为(1,2).他们一起索引了一个(2,2)块:
Here's what ix_
produces - a tuple of arrays, one is (2,1) in shape, the other (1,2). Together they index a (2,2) block:
In [76]: np.ix_([1,2],[2,3])
Out[76]:
(array([[1],
[2]]), array([[2, 3]]))
这篇关于以最pythonian方式编写ndarray的sub-ndarray.的Python 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!