Uys of Spades - 6 months ago 18
Python Question

# How to Create a Numpy Array from an existing Numpy Array

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

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