如何始终展平 numpy 数组? [英] How do I consistently flatten a numpy array?

查看:75
本文介绍了如何始终展平 numpy 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

from numpy import array, eye, matrix

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

打印 [1.0.].

另一方面,

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

打印 [[1 0]] 这是一个 1×2 数组.此外,

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

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

也打印[[1 0]].

这很烦人.为什么展平在这里失败,我还能如何将其变成一维形状?

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

推荐答案

停止使用 matrix.numpy.matrix.flatten 返回一个 1 行矩阵,因为它与 matrix 实例一样平坦.如果由于某种原因你死心塌地使用 matrix,请使用 matrix.A 展平前:

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()

或者直接使用A1直接得到一个扁平的ndarray:

or just use A1 to get a flat ndarray directly:

flat = whatever_matrix.A1

这篇关于如何始终展平 numpy 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆