[英]I want to rearrange an array according to row and column positions, how can I do it in Python?
In R I manage to do it, the idea is to do it in Python, if I apply M[index]
in Python, the order is different from the result in R. In R I manage to do it, the idea is to do it in Python, if I apply
M[index]
in Python, the order is different from the result in R.
Code in R: R 中的代码:
> M = matrix(c("a",0,"z",
+ 0,0,"b",
+ "c","y",0), nrow = 3, byrow = TRUE)
> M
[,1] [,2] [,3]
[1,] "a" "0" "z"
[2,] "0" "0" "b"
[3,] "c" "y" "0"
>
> index = c(3,2,1)
>
> M[index,index]
[,1] [,2] [,3]
[1,] "0" "y" "c"
[2,] "b" "0" "0"
[3,] "z" "0" "a"
>
Code in Python: Python 中的代码:
M = np.array([["a",0,"z"],
[0,0,"b"],
["c","y",0]])
index = [2,1,0]
print(M[index])
array([['c', 'y', '0'],
['0', '0', 'b'],
['a', '0', 'z']], dtype='<U1')
You can use np.flipud
and np.fliplr
:您可以使用
np.flipud
和np.fliplr
:
>>> M = np.array([["a",0,"z"],
[0,0,"b"],
["c","y",0]])
>>> np.fliplr(np.flipud(M))
array([['0', 'y', 'c'],
['b', '0', '0'],
['z', '0', 'a']], dtype='<U1')
Or you can rotate by 90 degrees, twice, with np.rot90
:或者您可以使用
np.rot90
旋转 90 度两次:
>>> np.rot90(M, 2)
array([['0', 'y', 'c'],
['b', '0', '0'],
['z', '0', 'a']], dtype='<U1')
If you prefer to do it by indices, you can do:如果你更喜欢通过索引来做,你可以这样做:
>>> index = [2,1,0]
>>> M[index, ::-1]
array([['0', 'y', 'c'],
['b', '0', '0'],
['z', '0', 'a']], dtype='<U1')
# or,
>>> M[::-1, index]
array([['0', 'y', 'c'],
['b', '0', '0'],
['z', '0', 'a']], dtype='<U1')
Which is, essentially, similar to:这本质上类似于:
>>> M[::-1, ::-1]
array([['0', 'y', 'c'],
['b', '0', '0'],
['z', '0', 'a']], dtype='<U1')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.