Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy.take range of array elements Python

I have an array of integers.

data = [10,20,30,40,50,60,70,80,90,100]

I want to extract a range of integers from the array and get a smaller array.

data_extracted = [20,30,40]

I tried numpy.take.

data = [10,20,30,40,50,60,70,80,90,100]
start = 1    # index of starting data entry (20)
end = 3      # index of ending data entry (40)
data_extracted = np.take(data,[start:end])

I get a syntax error pointing to the : in numpy.take.

Is there a better way to use numpy.take to store part of an array in a separate array?

like image 863
Spencer H Avatar asked Oct 28 '25 08:10

Spencer H


1 Answers

You can directly slice the list.

import numpy as np
data = [10,20,30,40,50,60,70,80,90,100]
data_extracted = np.array(data[1:4])

Also, you do not need to use numpy.array, you could just store the data in another list:

data_extracted = data[1:4]

If you want to use numpy.take, you have to pass it a list of the desired indices as second argument:

import numpy as np
data = [10,20,30,40,50,60,70,80,90,100]
data_extracted = np.take(data, [1, 2, 3])

I do not think numpy.take is needed for this application though.

like image 123
Tristan Avatar answered Oct 29 '25 21:10

Tristan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!