Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Numpy array copying not working for last column

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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  ]]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading