2

It seems like a simple question. But for me it is tricky... Sorry. I have a big ndarray with shape (2800, 256, 256, 3) which was filled with zeros. And I have a ndarray with shape (700, 256, 256, 3) with data. So I want copy data to the first array. In such way that only first 700 rows in the first array will be with data from the second array. So how?

Spinifex3
  • 91
  • 1
  • 1
  • 8

2 Answers2

1

You copy an array into a slice of another array with sliced indexing:

In [41]: arr = np.zeros((4,3,2), int)
In [42]: x = np.arange(12).reshape(2,3,2)
In [43]: arr[:2,:,:] = x
In [44]: arr
Out[44]: 
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]],

       [[ 0,  0],
        [ 0,  0],
        [ 0,  0]],

       [[ 0,  0],
        [ 0,  0],
        [ 0,  0]]])

arr[:2] = x works just as well, but sometimes it helps us humans to see what dimensions are being copied.

It doesn't have to be a slice, as long as the = immediately follows.

In [46]: arr[[0,2],:,:] = x
In [47]: arr
Out[47]: 
array([[[ 0,  1],
        [ 2,  3],
        [ 4,  5]],

       [[ 0,  0],
        [ 0,  0],
        [ 0,  0]],

       [[ 6,  7],
        [ 8,  9],
        [10, 11]],

       [[ 0,  0],
        [ 0,  0],
        [ 0,  0]]])
hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

I believe you can just do:

arr2 = arr1[:700,:,:,:].copy()

This slices the array along the first axis up to index 700, (which gives you the first 700 entries), and copies all of the other axes of those rows.

LizardCode
  • 28
  • 5