Reduce Dimensons when converting list to array

别等时光非礼了梦想. 提交于 2020-01-06 03:30:58

问题


I want to reduce the dimensions of an array after converting it to a list

a = np.array([[1,2],[3,4]])
print a.shape
b = np.array([[1],[3,4]])
print b.shape

Output:

(2, 2)
(2,)

I want a to have the same shape as b i.e. (2,)


回答1:


>>> a = np.array([[1,2],[3,4], None])[:2]
>>> a
array([[1, 2], [3, 4]], dtype=object)
>>> a.shape
(2,)

Works, though is probably the wrong way to do it (I'm a numpy newb).




回答2:


Do you understand what b is?

b = np.array([[1],[3,4]])
print(repr(b))

array([[1], [3, 4]], dtype=object)

b is a 1d array with 2 elements, each a list. np.array does this way because the 2 sublists have different length, so it can't create a 2d array.

a = np.array([[1,2],[3,4]])
print(repr(a)) 

array([[1, 2],
       [3, 4]])

Here the 2 sublists have the same length, so it can create a 2d array. Each element is an integer. np.array tries to create the highest dimensional array that the input allows.

Probably the best way to create another array like b is to make a copy, and insert the desired lists.

a1 = b.copy()
a1[0] = [1,2]
# a1[1] = [3,4]
print(repr(a1))

array([[1, 2], [3, 4]], dtype=object)

You have to use this convoluted method because you trying to do something 'unnatural'.

You comment about using vstack. Both work:

In [570]: np.vstack((a,b))   # (3,2) array
Out[570]: 
array([[1, 2],
       [3, 4],
       [[1], [3, 4]]], dtype=object)

In [571]: np.vstack((a1,b))   # (2,2) array
Out[571]: 
array([[[1, 2], [3, 4]],
       [[1], [3, 4]]], dtype=object)

Your array b is little more than the original list in an array wrapper. Is that really what you need? The 2d a is a normal numpy array. b is an oddball construction.



来源:https://stackoverflow.com/questions/30281481/reduce-dimensons-when-converting-list-to-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!