Numpy array copying not working for last column

Question:

I was trying to copy a specific range of columns for a particular row and copy to another array.
Apparently it is not working.

I have included a minimal working example below.

import numpy as np

A = np.random.rand(3,7)
B = np.ones([3,7])
B[2,3:-1] = A[2,3:-1]

print("A")
print (A)
print("B")
print (B)

OUTPUT was:

A
[[ 0.81316997  0.78075178  0.17835127  0.26448045  0.13750901  0.30405211
   0.36017253]
 [ 0.0167155   0.97254508  0.70175417  0.66376461  0.9168543   0.21314925
   0.46779966]
 [ 0.71477647  0.63700576  0.69320753  0.60782878  0.16999691  0.55042705
   0.26861216]]
B
[[ 1.          1.          1.          1.          1.          1.          1.        ]
 [ 1.          1.          1.          1.          1.          1.          1.        ]
 [ 1.          1.          1.          0.60782878  0.16999691  0.55042705   1.        ]]

The last value was not copied. Can anyone tell what is wrong here?
I was expecting

A
[[ 0.81316997  0.78075178  0.17835127  0.26448045  0.13750901  0.30405211
   0.36017253]
 [ 0.0167155   0.97254508  0.70175417  0.66376461  0.9168543   0.21314925
   0.46779966]
 [ 0.71477647  0.63700576  0.69320753  0.60782878  0.16999691  0.55042705
   0.26861216]]
B
[[ 1.          1.          1.          1.          1.          1.          1.        ]
 [ 1.          1.          1.          1.          1.          1.          1.        ]
 [ 1.          1.          1.          0.60782878  0.16999691  0.55042705  0.26861216  ]]

Asked By: Sumith Yesudasan

||

Answers:

In the slicing use [2,3:] instead of [2,3:-1] to include the last element.

This is because negative indices are counted backwards from the end of that list and you are ending the slice at the -1 index (which is the last). Python is exclusive so the end given isn’t included in the slice.

Answered By: user17301834
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.