简体   繁体   中英

How do I create a function to slice 2d arrays in python?

The only user input is the array itself, the first element of the slice and the last element of the slice?

Ie

x=np.array([[1,2,3,4],[5,6,7,8]])
def slicing_array(array, first_element, last_element):

Input:

slicing_array(x, 2, 8)

Output:

[2,3,4,6,7,8]

How about this?

import numpy as np

a = np.array([[3, 5, 2], [3, 2, 4]])
x = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])

def slicing_array(array, first_element, last_element):
    c = len(array[0])
    l = []
    for n in range(first_element, last_element + 1):
            l.append(array[(n-1) // c][(n-1) % c])
    return l

print(slicing_array(a, 2, 4))
print(slicing_array(x, 2, 8))

The result is as follows:

[5, 2, 3]
[2, 3, 4, 5, 6, 7, 8]

The simplest solution is to using indexing operations on a flattened array

a = np.asarray([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
def slicing_array(array, first_element, last_element):
    return array.flatten()[first_element:last_element]

slicing_array(a,2,7)
> array([3, 4, 5, 6, 7])

numpy has quite the extensive documentation on how you can index arrays: numpy indexing

You can use np.where to find coordinates of given first and last elements the use you them to find slice like:

def slicing_2d_array(arr, first_element, last_element):
    first_coords = np.where(arr == first_element)
    last_coords = np.where(arr == last_element)

    first_x, first_y = first_coords[0][0], first_coords[1][0]
    last_x, last_y = last_coords[0][0], last_coords[1][0]
    
    res = np.vstack(arr[first_x][first_y:last_y+1], arr[first_x+1][first_y:last_y+1])
    for i in range(first_x+1,last_x+1):
        np.vstack([res, arr[i][first_y:last_y+1]])
    return res

a = np.asarray([[1,2,3],[4,5,6],[7,8,9],[10,11,12]]) def slicing_array(array, first_element, last_element): return array.flatten()[first_element:last_element]

slicing_array(a,2,7)

array([3, 4, 5, 6, 7])

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