Anup Panwar
Anup Panwar

Reputation: 293

Python numpy array get first column values divide by 255 and store back

I have following numpy array

[[[  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]
   ..., 
  [  255   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]]]

and this is a large array i just gave a sort example here

I want to divide the first column first index value of every row by 255 and store it back to array,

Ex [ 255 0 0 255] take first column first index value 255/255 and store it back, same for all rows

[[[  0   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]
   ..., 
  [  1   0   0 255]
  [  0   0   0 255]
  [  0   0   0 255]]]

Upvotes: 0

Views: 2836

Answers (2)

jmd_dk
jmd_dk

Reputation: 13090

If you do something like a[:, :, 0] = a[:, :, 0]/255, the right-hand-side instantiates a whole new array, does the computation and then copies the result into a. You can skip this additional array instantiation and copying by using in-place division, which is done with the /= operator. Additionally, you may use ... while indexing to mean "every other dimension", so that your code work on arrays of arbitrary shape. In total:

a[..., 0] /= 255

Additionally, you could consider using //= instead of just /=, to indicate that this is an integer division. These are equivalent for NumPy integer arrays, but not for NumPy float arrays.

Upvotes: 1

wim
wim

Reputation: 362507

This can be done with in-place division:

>>> a = np.array([[255,255],[0,255]], dtype=int)
>>> a
array([[255, 255],
       [  0, 255]])
>>> a[:, 0] /= 255
>>> a
array([[  1, 255],
       [  0, 255]])

Upvotes: 4

Related Questions