Home > Back-end >  Python split array into smaller arrays
Python split array into smaller arrays

Time:07-08

I am trying to split a numpy array named K into three different numpy arrays Kff, Kpp and Kpf. I have attached an image of how they need to be split up here: https://i.imgur.com/kbJnljf.png

For example to set up Kff I need the following entries from K:

  • i = 2, 3, 4, 5 and 7
  • j = 2, 3, 4, 5 and 7

I am completely lost at to how I can do this in a quick and efficient manner. Eventually I will have to do something similiar for a 24x24 array.

CodePudding user response:

import numpy as np

k = np.arange(1, 65).reshape(8, 8)
rows = [True, True, False, False, False, False, True, False]
cols = [True, True, False, False, False, False, True, False]
notRows = [not x for x in rows]
notCols = [not x for x in cols]
k_pp = k[rows, :][:, cols]
k_ff = k[notRows, :][:, notCols]
k_pf = k[rows, :][:, notCols]

print(f"{k=}\n{k_pp=}\n{k_ff=}\n{k_pf=}")

outputs

k=array([[ 1,  2,  3,  4,  5,  6,  7,  8],
         [ 9, 10, 11, 12, 13, 14, 15, 16],
         [17, 18, 19, 20, 21, 22, 23, 24],
         [25, 26, 27, 28, 29, 30, 31, 32],
         [33, 34, 35, 36, 37, 38, 39, 40],
         [41, 42, 43, 44, 45, 46, 47, 48],
         [49, 50, 51, 52, 53, 54, 55, 56],
         [57, 58, 59, 60, 61, 62, 63, 64]])
k_pp=array([[ 1,  2,  7],
            [ 9, 10, 15],
            [49, 50, 55]])
k_ff=array([[19, 20, 21, 22, 24],
            [27, 28, 29, 30, 32],
            [35, 36, 37, 38, 40],
            [43, 44, 45, 46, 48],
            [59, 60, 61, 62, 64]])
k_pf=array([[ 3,  4,  5,  6,  8],
            [11, 12, 13, 14, 16],
            [51, 52, 53, 54, 56]])

more synthetically:

import numpy as np

k = np.arange(1, 65).reshape(8, 8)
rows = np.array([True, True, False, False, False, False, True, False])
cols = np.array([True, True, False, False, False, False, True, False])
k_pp = k[rows, :][:, cols]
k_ff = k[~rows, :][:, ~cols]
k_pf = k[rows, :][:, ~cols]

print(f"{k=}\n{k_pp=}\n{k_ff=}\n{k_pf=}")
  • Related