[Python] Numpyic way to take the first N rows and columns out of every M rows and columns from...

Discussão em 'Python' iniciado por Stack, Junho 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have a 20 x 20 square matrix. I want to take the first 2 rows and columns out of every 5 rows and columns, which means the output should be a 8 x 8 square matrix. This can be done in 2 consecutive steps as follows:

    import numpy as np

    m = 5
    n = 2
    A = np.arange(400).reshape(20,-1)
    B = np.asarray([row for i, row in enumerate(A) if i % m < n])
    C = np.asarray([col for j, col in enumerate(B.T) if j % m < n]).T


    However, I am looking for efficiency. Is there a more Numpyic way to do this? I would prefer to do this in one step.

    Continue reading...

Compartilhe esta Página