[英]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.