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?
Asked
Active
Viewed 1.2k times
2
-
Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – ivan_pozdeev Mar 28 '18 at 19:38
-
No! I want that initial array will be with shape 2800, not 700. – Spinifex3 Mar 28 '18 at 19:40
-
https://stackoverflow.com/questions/40690248/copy-numpy-array-into-part-of-another-array – ivan_pozdeev Mar 28 '18 at 19:41
2 Answers
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
-
1To make a copy rather than a view you need `arr2 = arr1[:700,:,:,:].copy()` – xnx Mar 28 '18 at 19:40
-
-
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 – Spinifex3 Mar 28 '18 at 19:46
-
-
-
Zeros in the first 700 rows? Are you sure they weren't in the second array you copied in? – xnx Mar 28 '18 at 20:01