0

Lets say that we have the following numpy array:

[[ 0  0  0]
 [ 1  0  0]
 [ 2  0  0]
 [ 3  0  0]
 [ 4  0  0]
 [ 5  0  0]
 [ 6  0  0]
 [ 7  0  0]
 [ 8  0  0]
 [ 9  0  0]
 [10  0  0]
 [11  0  0]
 [12  0  0]
 [13  0  0]]

How can i insert this np.array

[[0 45]
 [1 34]
 [2 23]
 [3 56]
 [4 45]
 [5 34]]

staring from index nr 3 on column 1 and column 2 so that in the end it will look like this:

[[ 0  0  0]
 [ 1  0  0]
 [ 2  0  45]
 [ 3  1  34]
 [ 4  2  23]
 [ 5  3  56]
 [ 6  4  45]
 [ 7  5  34]
 [ 8  0  0]
 [ 9  0  0]
 [10  0  0]
 [11  0  0]
 [12  0  0]]

The idea is that i would like to specify the index nr where the second array should be placed in the first one. I would a appreciate a solution which takes into account the speed of execution. Both arrays are have a few million rows, the first array is always bigger than the second one.

4
  • I wonder where these arrays may be coming from ;-) Commented Feb 9, 2017 at 3:51
  • Hi @PaulPanzer :),yes they are coming from the GPU solution. With the CPU solution i didn't have to split data1. but with the GPU, i have to send data1 in blocks of around 3mil rows and so after that i must put the result back in the original array to get the original index nr Commented Feb 9, 2017 at 7:47
  • 1
    What? Did you account for these overheads in your benchmarks? I demand a recount! :-P Commented Feb 9, 2017 at 7:53
  • The overheads are insignificant because data1 is splited in max 3 or 4 blocks, so the only overhead i have is when i put the result back in the original index array which is again only 3-4 blocks per data1 and the speed of doing that is close to 0 Commented Feb 9, 2017 at 7:56

1 Answer 1

3

Just define the recipient space with sliced indexing:

In [79]: arr = np.zeros((10,3),int)    
In [80]: b = np.ones((4,2), int)
In [81]: nr = 3
In [82]: arr[nr:nr+b.shape[0], 1:] = b

In [83]: arr
Out[83]: 
array([[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0],
       [0, 1, 1],
       [0, 1, 1],
       [0, 1, 1],
       [0, 1, 1],
       [0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]])

Just make sure the shapes match:

In [84]: arr[nr:nr+b.shape[0], 1:].shape
Out[84]: (4, 2)

In [85]: b.shape
Out[85]: (4, 2)

You could refine the indexing to handle the case where nr is too large to fit all of b in the arr.

Sign up to request clarification or add additional context in comments.

Comments

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.