简体   繁体   English

沿所有轴无缝高效地翻转numpy数组或稀疏矩阵

[英]Seamlessly and efficiently flipping numpy array or sparse matrix along all axes

Let's say we have a matrix (numpy array) of unknown shape, the shape can be for example (1,5) (row), (5,1) (column), (5,5) (square), (5,6) (non-square) or (5,) (degenerated) (ok the last case isn't a matrix but is a valid input). 假设我们有一个形状未知的矩阵(numpy数组),形状可以是(1,5) (行), (5,1) (列), (5,5) (正方形), (5,6) (非正方形)或(5,) (退化)(好的,最后一种情况不是矩阵,而是有效输入)。

I would like to given a matrix of any shape (column, row, square, nonsquare, degenerated). 我想给出任何形状的矩阵(列,行,正方形,非正方形,退化)。 I will return a flipped up/down left/right version of it. 我将返回其上下左右翻转的版本。

Since np.flip has some issues with 1d arrays. 由于np.flip对于1d数组存在一些问题。 My approach was: 我的方法是:

def flipit(M):
    return M.ravel()[::-1].reshape(M.shape)

It works, but is that acceptable? 它有效,但是可以接受吗? Any faster ways to do it? 有更快的方法吗?

In the other hand, how can I do the same for sparse matrices (for example if M is scipy.sparse.csr_matrix ). 另一方面,如何对稀疏矩阵执行相同操作(例如,如果Mscipy.sparse.csr_matrix )。

We can use slice notation with a step-size of -1 for the number of dims in the input to flip along all the axes, as that's what the original code is essentially doing. 我们可以使用切片符号,步长为-1来表示输入中沿所有轴翻转的暗淡数,因为这就是原始代码的本质所在。 This would cover both arrays and sparse matrices - 这将覆盖数组和稀疏矩阵-

def flip_allaxes(a): # a can be array or sparse matrix
    # generate flipping slice
    sl = slice(None,None,-1) # or np.s_[::-1] suggested by @kmario23
    return a[tuple([sl]*a.ndim)]

Simplified on newer NumPy versions (15.1 onwards) 在新的NumPy版本上简化(从15.1开始)

On newer NumPy versions : Version 15.1 and newer , that allows us to specify tuple of ints for the axes along which the flipping is needed. 在较新的NumPy版本上: Version 15.1和较新版本 ,它使我们能够为需要沿其翻转的轴指定一个整数元组。 For the default case with axis=None from the docs , it flips along all axes. 对于docs axis=None的默认情况,它将沿所有轴翻转。 Thus, to solve our case, it would be simply np.flip(a) and this would again cover both generic ndarrays and sparse matrices. 因此,要解决我们的情况,将只是np.flip(a) ,它将再次覆盖通用ndarrays和稀疏矩阵。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM