2

I am looking to take an existing numpy array and create a new array from the existing array but at start and end from values from the existing array?

For example:

arr = np.array([1,2,3,4,5,6,7,8,9,10])

def split(array):
    # I am only interested in 4 thru 8 in original array
    return new_array

>>>new_array
>>> array([4,5,6,7,8])
1
  • 2
    arr[3:8] or arr[3:8].copy() if you want a copy, not a view. Commented May 7, 2016 at 6:27

2 Answers 2

1

Just do this :

arr1=arr[x:y]

where,

x -> Start index

y -> end index

Example :

>>> import numpy as np
>>> arr = np.array([1,2,3,4,5,6,7,8,9,10])
>>> arr
array([ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10])
>>> arr1=arr[3:8]
>>> arr1
array([4, 5, 6, 7, 8])

In the above case we are using assignment, assignment statements in Python do not copy objects, they create bindings between a target and an object.

You may use a .copy() to do a shallow copy.

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

i.e.

>>> arr1=arr[3:8].copy()
>>> arr1
array([4, 5, 6, 7, 8])

You may use deepcopy() to do a deep copy.

A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.

i.e.

>>> arr2 = deepcopy(arr[3:8])
>>> lst2
array([4, 5, 6, 7, 8])

Further reference :

copy — Shallow and deep copy operations

Shallow and Deep Copy

Sign up to request clarification or add additional context in comments.

3 Comments

deepcopy matters with lists, but not with numpy arrays.
Yes, list of lists specially. Just put it all up for reference. copy() is the solution to the question.
Technically arr1 is a new array (with its own shape and id), but it shares the underlying data buffer with arr. But arr1 = arr[[3,4,5]] would be full copy. In the long run it is important to understand the difference between a numpy view and copy.
0

You need to slice and copy the array. First the slice, as mentioned by @AniMenon can be achieved with the colonized index.

Next the copy, you have the option of using the builtin .copy() or importing copy and using copy.copy().

Either way this is an important step to avoiding unexpected interconnections later on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.