[英]How can I assign multiple rows and columns of one array to the same rows and columns of another array in Python?
As the title says, how do I assign multiple rows and columns of one array to the same rows and columns of another array in Python?正如标题所说,如何将一个数组的多个行和列分配给 Python 中另一个数组的相同行和列?
I want to do the following:我想做以下事情:
Kn[0, 0] = KeTrans[startPosRow, startPosCol];
Kn[0, 1] = KeTrans[startPosRow, endPosCol];
Kn[1, 0] = KeTrans[endPosRow, startPosCol];
Kn[1, 1] = KeTrans[endPosRow, endPosCol];
Kn is a 2X2 matrix and KeTrans is a 4X4. Kn 是 2X2 矩阵,KeTrans 是 4X4。
I tried the following but with no luck.我尝试了以下但没有运气。
Kn[0:1, 0:1] = KeTrans[startPosRow: endPosRow, startPosCol: endPosCol]
For multi-dimensional arrays, I highly suggest use Numpy.对于多维 arrays,我强烈建议使用 Numpy。
import numpy as np
To create an Nth-dimensional array:创建第 N 维数组:
a = np.array([4,2,4],[23,4,3,2]...,[2,3,4])
The array are indexed very intuitively:数组的索引非常直观:
>> a[0,1]
4
You can even do slicing for the np array.您甚至可以对 np 数组进行切片。
documentation of numpy multi-dimensional array: https://numpy.org/doc/stable/reference/arrays.ndarray.html numpy 多维数组的文档: https://numpy.org/doc/stable/reference/arrays.ndarray.html
But they're not the same rows and columns:-) (unless startPosRow
and friends have very specific values).但它们不是相同的行和列:-)(除非
startPosRow
和朋友有非常具体的值)。
The problem is that the slice startPosRow:endPosRow
(for example) does not mean "element startPosRow
and element endPosRow
".问题是切片
startPosRow:endPosRow
(例如)并不意味着“元素startPosRow
和元素endPosRow
”。 It means "elements in range(startPosRow, endPosRow)
", which doesn't include endPosRow
and which typically has more than two matching indices.它的意思是“
range(startPosRow, endPosRow)
”,它不包括endPosRow
并且通常具有两个以上的匹配索引。
If you just want the four corners, you could use slices with a step size:如果你只想要四个角,你可以使用带步长的切片:
Kn[0:1, 0:1] = KeTrans[startPosRow:endPosRow + 1:endPosRow - startPosRow,
startPosCol:endPosCol + 1:endPosCol - startPosCol]
Is this what you are trying to do:这是你想要做的:
In [323]: X = np.arange(16).reshape(4,4)
In [324]: Y = np.zeros((2,2),int)
In [325]: Y[:] = X[:2,:2]
In [326]: Y
Out[326]:
array([[0, 1],
[4, 5]])
In [327]: Y[:] = X[1:3,2:]
In [328]: Y
Out[328]:
array([[ 6, 7],
[10, 11]])
For reference以供参考
In [329]: X
Out[329]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.