【问题标题】:I want to rearrange an array according to row and column positions, how can I do it in Python?我想根据行和列位置重新排列数组,我该如何在 Python 中做到这一点?
【发布时间】:2020-11-14 23:31:19
【问题描述】:

在 R 中我设法做到了,想法是在 Python 中做到,如果我在 Python 中应用 M[index],则顺序与 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" 
> 

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')

【问题讨论】:

标签: python r python-3.x matrix


【解决方案1】:

您可以使用np.flipudnp.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')

或者您可以使用np.rot90 旋转两次 90 度:

>>> np.rot90(M, 2)
array([['0', 'y', 'c'],
       ['b', '0', '0'],
       ['z', '0', 'a']], dtype='<U1')

如果你更喜欢通过索引来做,你可以这样做:

>>> 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')

本质上类似于:

>>> M[::-1, ::-1]
array([['0', 'y', 'c'],
       ['b', '0', '0'],
       ['z', '0', 'a']], dtype='<U1')

【讨论】:

  • 非常感谢您的帮助。但是如果我像这样更改索引的顺序会发生什么index = [2,0,1] 该方法对我不再有用。 array([['c', 'y', '0'], ['a', '0', 'z'], ['0', '0', 'b']], dtype='&lt;U1') 真实结果是:[[ "0" "c" "y" ],[ "z" "a" "0" ],["b" "0" "0"]]
  • M[[2,0,1],:][:,[2,0,1]]
猜你喜欢
  • 1970-01-01
  • 2021-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 2019-07-25
  • 1970-01-01
相关资源
最近更新 更多