Python中的维度不一致(有时显示1D,有时显示3D)
我有一个列表,列表中的每个元素都是一个2D矩阵Python中的维度不一致(有时显示1D,有时显示3D),python,numpy,arraylist,data-science,Python,Numpy,Arraylist,Data Science,我有一个列表,列表中的每个元素都是一个2D矩阵 np.shape(mylist) >>(5000,) np.shape(mylist[0]) >>(62,62) type(mylist) >> list type(mylist[0]) >> numpy.ndarray 现在,我正在尝试创建一个索引列表,该列表显示在索引列表中: y_train = [mylist[i] for i in index] 问题是,有时它显示1D形状,有时显示
np.shape(mylist)
>>(5000,)
np.shape(mylist[0])
>>(62,62)
type(mylist)
>> list
type(mylist[0])
>> numpy.ndarray
现在,我正在尝试创建一个索引列表,该列表显示在索引列表中:
y_train = [mylist[i] for i in index]
问题是,有时它显示1D形状,有时显示3D形状(例如,(nx,)或(nx,ny,nz))
例如:
yy = []
yy.append(mylist[17])
yy.append(mylist[1381])
print(np.shape(yy))
>> (2,)
yy = []
yy.append(mylist[17])
yy.append(mylist[1380])
print(np.shape(yy))
>> (2, 513, 513)
知道为什么吗?也许事实上mylist[17]和mylist[1380]的形状相同,而mylist[17]和mylist[1381]的形状不同?首先是两个数组具有不同形状的简单情况:
In [204]: alist = [np.ones((2,3),int), np.zeros((1,3),int)]
In [205]: alist
Out[205]:
[array([[1, 1, 1],
[1, 1, 1]]), array([[0, 0, 0]])]
In [206]: len(alist)
Out[206]: 2
In [207]: np.shape(alist)
Out[207]: (2,)
In [208]: alist.shape
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-208-6ab8dc5f9201> in <module>()
----> 1 alist.shape
AttributeError: 'list' object has no attribute 'shape'
In [209]: np.array(alist)
Out[209]:
array([array([[1, 1, 1],
[1, 1, 1]]), array([[0, 0, 0]])], dtype=object)
alist
仍然没有shape`属性。是。另外,为什么还要在python列表中调用np.shape
?您应该使用len
来进行此操作。在numpy阵列上使用形状保留。也不要使用numpy.shape()
,直接使用ndarray.shape
。第4行的输出是什么?np.shape(alist)
首先将alist
转换为numpy
数组,然后返回shape
属性。如果列表中的元素都具有相同的二维形状,则列表转换的数组将是三维的,如果它们的形状不同,则将是1d对象数据类型数组。
In [210]: alist = [np.ones((2,3),int), np.zeros((2,3),int)]
In [211]: alist
Out[211]:
[array([[1, 1, 1],
[1, 1, 1]]), array([[0, 0, 0],
[0, 0, 0]])]
In [212]: len(alist)
Out[212]: 2
In [213]: np.shape(alist)
Out[213]: (2, 2, 3)
In [214]: np.array(alist)
Out[214]:
array([[[1, 1, 1],
[1, 1, 1]],
[[0, 0, 0],
[0, 0, 0]]])