簡體   English   中英

如何創建 function 以在 python 中切片 2d arrays?

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

唯一的用戶輸入是數組本身,切片的第一個元素和切片的最后一個元素?

IE

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

輸入:

slicing_array(x, 2, 8)

Output:

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

這個怎么樣?

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

結果如下:

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

最簡單的解決方案是在展平數組上使用索引操作

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 有關於如何索引 arrays 的大量文檔: numpy 索引

您可以使用 np.where 來查找給定的第一個和最后一個元素的坐標,然后使用它們來查找切片,例如:

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):返回 array.flatten()[first_element:last_element]

slicing_array(a,2,7)

數組([3, 4, 5, 6, 7])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM