【问题标题】:Python ndarray dtype and buffer question - it returns different valuesPython ndarray dtype 和缓冲区问题 - 它返回不同的值
【发布时间】:2020-06-24 03:03:29
【问题描述】:

所以我正在尝试使用以下代码创建一个 numpy darray 对象:

a = np.ndarray(shape=(3,3),dtype='float32',buffer=np.array([[100,2,3],[4,5,6],[7,8,9]]))

这将返回以下内容:

[[1.4e-43 0.0e+00 2.8e-45]
 [0.0e+00 4.2e-45 0.0e+00]
 [5.6e-45 0.0e+00 7.0e-45]]

为什么它返回的值与我指定的不同?

似乎 float32 正在改变一些事情,因为当 dtype='int' 像这样:

a = np.ndarray(shape=(3,3),dtype='int',buffer=np.array([[100,2,3],[4,5,6],[7,8,9]]))

这会返回正确的内容,例如:

[[100   2   3]
 [  4   5   6]
 [  7   8   9]]

为什么当 dtype='float32' 时它不起作用?

【问题讨论】:

  • 因为您正在传递一个具有 dtype=float32 的缓冲区...为什么您期望它的工作方式有所不同?为什么要使用 numpy.ndarray 构造函数开始?为什么不np.array([[100,2,3],[4,5,6],[7,8,9]], dtype='float32')???

标签: python buffer numpy-ndarray dtype


【解决方案1】:

在当前状态下,a 只不过是一个 dtype 为“float32”的随机数数组。 第一种情况的错误是因为您提供的 dtype='float32' 和 np.array() 的默认 dtype='int64' 不匹配。 要获得所需的结果,您应该在 np.array() dtype='float32'

中添加参数
    a = np.ndarray(size=(3, 3), dtype='float32' buffer=np.array([[100, 2, 3], 
    [4, 5, 6], [7, 8, 9]], dtype='float32')

    [[100., 2., 3.]
     [4., 5., 6.]
     [7., 8., 9.]]

请记住,a 的 dataType 将是浮点数,这就是我们最后使用小数的原因。

第二种情况有效,因为 dtype='int' 这是 np.array() 的默认 dtype。所以数据类型匹配并且有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-17
    • 1970-01-01
    • 2016-07-31
    • 2016-01-31
    • 2016-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多