Home > OS >  adding a value to numpy array
adding a value to numpy array

Time:05-17

I am trying to learn numpy slicing and indexing.

Below is the array that I have.

array = ([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])

How do I select the indices from 1 to 5(including 5) and the indices from 15 to 20 (including the element in the 20 index) in array and add 50 to only those values and display the new array?

I have tried the following;

newArr  = array[:6]
newaArr1 = array[15:21]

addarr = np.concatenate(newArr, newArr1)

This does not give me the full array. Can I get some help here?

CodePudding user response:

You could try:

import numpy

arr = ([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])
newArr  = arr[:6]   
newArr1  = arr[15:21]   
addArr = [newArr, newArr1]
addArr = numpy.array([item for sublist in addArr for item in sublist])   50
addArr

array([50, 51, 52, 53, 54, 55, 65, 66, 67, 68, 69, 70])

CodePudding user response:

(
# select the indices from 1 to 5(including 5)
array[1:5 1]
# add 50 to only those values
 = 50
)

# same for the other portion
array[15:21]  = 50

This will modify array in-place.


Example

>>> import numpy as np
>>> array = np.array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25])
>>> array[1:5 1]  = 50
>>> array[15:21]  = 50
>>> array
array([ 0, 51, 52, 53, 54, 55,  6,  7,  8,  9, 10, 11, 12, 13, 14, 65, 66,
       67, 68, 69, 70, 21, 22, 23, 24, 25])

CodePudding user response:

IIUC, you can do it by np.concatenate or np.hstack as:

np.concatenate((newArr, newArr1))   50

# [50 51 52 53 54 55 65 66 67 68 69 70]
  • Related