猿问

如何删除子数组的末尾元素?

所以我创建了一个 numpy 数组:

import numpy as np

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

我正在尝试删除此数组子数组的末尾元素:

a[0] = (a[0])[:-1]

并遇到这个问题:

a[0] = (a[0])[:-1] ValueError: 无法将输入数组从形状 (2) 广播到形状 (3)

为什么我不能改变它?我该怎么做?


陪伴而非守候
浏览 140回答 3
3回答

慕婉清6462132

鉴于:>>> aarray([[1, 2, 3],       [4, 5, 6],       [7, 8, 9]])你可以做:>>> a[:,0:2]array([[1, 2],       [4, 5],       [7, 8]])或者:>>> np.delete(a,2,1)array([[1, 2],       [4, 5],       [7, 8]])然后在任何一种情况下,将其分配回,a因为结果是一个新数组。所以:>>> a=a[:,0:2]>>> aarray([[1, 2],       [4, 5],       [7, 8]])如果您只想删除3第一行,那就是另一个问题了。如果你有一个 python 列表数组,你只能这样做,因为子列表的长度不同。例子:>>> a = np.array([[1,2],[4,5,6],[7,8,9]])>>> aarray([list([1, 2]), list([4, 5, 6]), list([7, 8, 9])], dtype=object)如果你这样做,就坚持使用 Python。您将失去 Numpy 的所有速度和其他优势。如果“通用”是指 N x M 数组每一行的最后一个元素,只需使用它.shape来查找维度:>>> aarray([[ 1,  2,  3,  4],       [ 5,  6,  7,  8],       [ 9, 10, 11, 12]])>>> a.shape(3, 4)>>> np.delete(a,a.shape[1]-1,1)array([[ 1,  2,  3],       [ 5,  6,  7],       [ 9, 10, 11]])或者,>>> a[:,0:a.shape[1]-1]array([[ 1,  2,  3],       [ 5,  6,  7],       [ 9, 10, 11]])

天涯尽头无女友

>>> a = np.array([[1,2,3],[4,5,6],[7,8,9]])>>> aarray([[1, 2, 3],&nbsp; &nbsp; &nbsp; &nbsp;[4, 5, 6],&nbsp; &nbsp; &nbsp; &nbsp;[7, 8, 9]])>>> type(a)<class 'numpy.ndarray'>>>> a.shape(3, 3)变量a是矩阵(二维数组)。它有一定数量的行和列。在矩阵中,所有行的长度必须相同。因此,在上面的示例中,如果第一行的长度为 2,其他行的长度为 3,则无法形成矩阵。因此,仅删除第一个(或任何其他子集)子数组的最后一个元素是不可能的。相反,您必须同时删除所有子数组的最后一个元素。可以这样做>>> a[:,0:2]array([[1, 2],&nbsp; &nbsp; &nbsp; &nbsp;[4, 5],&nbsp; &nbsp; &nbsp; &nbsp;[7, 8]])或者,>>> np.delete(a,2,1)array([[1, 2],&nbsp; &nbsp; &nbsp; &nbsp;[4, 5],&nbsp; &nbsp; &nbsp; &nbsp;[7, 8]])这也适用于其他位置的元素。可以删除子数组的任何元素,记住所有子数组应该具有相同的长度。但是,除非形状保持不变,否则您可以操作任何子数组的最后一个元素(或任何其他元素)。>>> a[0][-1] = 19>>> aarray([[ 1,&nbsp; 2, 19],&nbsp; &nbsp; &nbsp; &nbsp;[ 4,&nbsp; 5,&nbsp; 6],&nbsp; &nbsp; &nbsp; &nbsp;[ 7,&nbsp; 8,&nbsp; 9]])如果您尝试形成一个具有不等长行的矩阵,则会形成一个一维列表数组,在该列表上没有任何 Numpy 操作(如矢量处理、切片等)起作用(列表操作起作用)>>> b = np.array([[1,2,3],[1,2,3]])>>> c = np.array([[1,2],[1,2,3]])>>> barray([[1, 2, 3],&nbsp; &nbsp; &nbsp; &nbsp;[1, 2, 3]])>>> b.shape(2, 3)>>> carray([list([1, 2]), list([1, 2, 3])], dtype=object)>>> c.shape(2,)>>> print(type(b),type(c))<class 'numpy.ndarray'> <class 'numpy.ndarray'>两者都是 ndarray,但您可以看到第二个变量c是一维列表数组。>>> b+barray([[2, 4, 6],&nbsp; &nbsp; &nbsp; &nbsp;[2, 4, 6]])>>> c+carray([list([1, 2, 1, 2]), list([1, 2, 3, 1, 2, 3])], dtype=object)类似地, operation 执行withb+b的逐元素加法,但执行两个列表之间的连接操作。bbc+c

芜湖不芜

方法如下:import numpy as npa = np.array([[1,2,3],[4,5,6],[7,8,9]])a = a[:-1]print(a)输出:[[1 2 3]&nbsp;[4 5 6]]
随时随地看视频慕课网APP

相关分类

Python
我要回答