将空列表附加到numpy.array

时间:2017-02-18 17:44:17

标签: python arrays numpy

我试图弄清楚如何将空列表附加到已经存在的numpy数组

我可以为任何列表b

获取数组
a = np.array([b])
a = np.append(a, [])
print a # you get array([a, []])

此代码只输出原始[a]而不是[a,[]]。有谁知道这是如何实现的?

1 个答案:

答案 0 :(得分:1)

在数组中有一个空列表的唯一方法是创建一个对象dtype数组。

In [382]: a = np.empty((3,),dtype=object)
In [383]: a
Out[383]: array([None, None, None], dtype=object)
In [384]: a[0]=[1,2,3]
In [385]: a[1]=[]
In [386]: a
Out[386]: array([[1, 2, 3], [], None], dtype=object)

或列表(不同长度)

In [393]: np.array([[1,2,3],[]])
Out[393]: array([[1, 2, 3], []], dtype=object)

您可以将一个对象数组连接到另一个对象数组:

In [394]: a = np.empty((1,),object); a[0]=[1,2,3]
In [395]: a
Out[395]: array([[1, 2, 3]], dtype=object)
In [396]: b = np.empty((1,),object); b[0]=[]
In [397]: b
Out[397]: array([[]], dtype=object)
In [398]: np.concatenate((a,b))
Out[398]: array([[1, 2, 3], []], dtype=object)

np.append包裹concatenate,旨在为另一个数组添加标量。它对清单或其他清单的作用是不可预测的。

我把最后一条评论带回来; np.append将列表转换为简单数组。这些都做同样的事情

In [413]: alist=[1,2]
In [414]: np.append(a,alist)
Out[414]: array([[1, 2, 3], 1, 2], dtype=object)
In [415]: np.concatenate((a, np.ravel(alist)))
Out[415]: array([[1, 2, 3], 1, 2], dtype=object)
In [416]: np.concatenate((a, np.array(alist)))
Out[416]: array([[1, 2, 3], 1, 2], dtype=object)