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?
-
Possible duplicate of How to clone or copy a list?ivan_pozdeev– ivan_pozdeev2018-03-28 19:38:22 +00:00Commented Mar 28, 2018 at 19:38
-
No! I want that initial array will be with shape 2800, not 700.Spinifex3– Spinifex32018-03-28 19:40:13 +00:00Commented Mar 28, 2018 at 19:40
-
stackoverflow.com/questions/40690248/…ivan_pozdeev– ivan_pozdeev2018-03-28 19:41:28 +00:00Commented Mar 28, 2018 at 19:41
Add a comment
|
2 Answers
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]]])
Comments
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
xnx
To make a copy rather than a view you need
arr2 = arr1[:700,:,:,:].copy()ivan_pozdeev
I believe it should be the other way round.
Spinifex3
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
xnx
Then you just want
arr[:700,...] = arr2 don't you?Spinifex3
@xnx It is not working. There are still zeros in the first array.
|