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?

3

2 Answers 2

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]]])
Sign up to request clarification or add additional context in comments.

Comments

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.

6 Comments

To make a copy rather than a view you need arr2 = arr1[:700,:,:,:].copy()
I believe it should be the other way round.
No! I dont want dimensions in the first array. After your descision it will have shape (700, 256, 256, 3). But I want (2800, 256, 256, 3) where only first 700 rows contains data. @LizardCode
Then you just want arr[:700,...] = arr2 don't you?
@xnx It is not working. There are still zeros in the first array.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.