1

I have created a very large NumPy array of size 500 x 10000, called first_array, to solve a partial differential equation using the Crank Nicolson method. This method needs to create and use all the data stored in the array, but I only need a small part of it. For example, 50 rows and 50 columns would be enough.

How could I create a smaller array, second_array, from first_array by selecting only those rows and columns that are multiples of a certain number? Is there any built-in NumPy method for this task?

For example, if first_array is

array([[11, 12, 13, 14],
       [21, 22, 23, 24],
       [31, 32, 33, 34],
       [14, 42, 43, 44]])

then I would like second_array to be an array formed with the 1st and 3d rows of first_array and with the 2ns and 4th column of first_array:

array([[12, 14],
       [32, 34],])
User1234321
  • 321
  • 1
  • 10

2 Answers2

1

Something like this

import numpy as np

first_array = np.random.rand(500,1000)
row_factor = 10
row_start = 1
col_factor = 10
col_start = 1
second_array = first_array[row_start:-1:row_factor,col_start:-1:col_factor]
print(second_array.shape)

You can make simple slicing where you skip row_factor or col_factor in both direction

ymmx
  • 4,769
  • 5
  • 32
  • 64
  • It works perfectly with 2D arrays! Could it also be applied to 1D arrays? I tried `1D_array[col_start:-1:col_factor]`, but didn't work. – User1234321 May 10 '22 at 12:53
  • 1
    You cannot name a variable starting with a number. but it works `import numpy as np D1_array = np.random.rand(500) col_factor = 10 col_start = 1 D2_array = D1_array[col_start:-1:col_factor]` – ymmx May 10 '22 at 12:56
1

You can do it as such:

import numpy as np
x = np.arange(100).reshape(10,10)
y = x[slice(0,-1,3), slice(0,-1,4)].copy()

Now you have selected every row which is a multiple of 3, and every column which is a multiple of 4. You can adjust the slice start and end points if you want to start at a specific offset.

Note: you need to use .copy() if you want to avoid modifying the original array x. Otherwise slices are just a view to the original array.

System123
  • 523
  • 5
  • 14