简体   繁体   中英

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.

ie

>>> 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.

ie

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

Further reference :

copy — Shallow and deep copy operations

Shallow and Deep Copy

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM