How do I consistently flatten a numpy array?

泪湿孤枕 提交于 2019-12-01 08:33:30

问题


from numpy import array, eye, matrix

x = array([1, 0])
A = eye(2)
print(A.dot(x))

prints [1. 0.].

On the other hand,

B = matrix([[1, 0], [0, 1]])
print(B.dot(x))

prints [[1 0]] which is a 1-by-2 array. Furthermore,

print(B.dot(x).flatten())

also prints [[1 0]].

This is rather annoying. Why does flatten fail here and how else can I get this into the 1-d shape?


回答1:


Stop using matrix. numpy.matrix.flatten returns a 1-row matrix, because that's as flat as matrix instances get. If for some reason you are dead set on using matrix, convert to ndarray with matrix.A before flattening:

flat = whatever_matrix.A.flatten()

or just use A1 to get a flat ndarray directly:

flat = whatever_matrix.A1


来源:https://stackoverflow.com/questions/50453626/how-do-i-consistently-flatten-a-numpy-array

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