【问题标题】:NumPy: array assignment issue when using custom dtypeNumPy:使用自定义 dtype 时的数组分配问题
【发布时间】:2011-11-05 08:47:48
【问题描述】:

我在 NumPy 和 ndarray 的自定义 dtype 中发现了以下令人费解的行为:

import numpy as np

# Make a custom dtype with a single triplet of floats (my actual dtype has other
# components, but this suffices to demonstrate the problem.
dt = np.dtype([('a', np.float64, 3)])

# Make a zero array with this dtype:
points = np.zeros((4, 4), dtype=dt)

# Try to edit an entry:
points[0][0]['a'] = np.array([1, 1, 1])

print points[0][0]['a']

现在,这返回为不包含 [1。 1. 1.] 正如我所期望的那样,而是 [1. 0. 0.],只对第一个坐标进行赋值。我可以通过按坐标执行分配来解决这个问题,但考虑到在这种情况下完全分配肯定应该是默认行为,这似乎是不必要的。

对这里发生的事情有什么想法吗?

【问题讨论】:

    标签: python arrays multidimensional-array numpy


    【解决方案1】:

    如果您更改索引的顺序,如下所示:points['a'][0][0] = np.array([1, 1, 1]),它适用于我(python 2.6.5,Ubuntu 10.04 上的 numpy 1.3.0)。我希望我知道为什么。

    【讨论】:

    • 也适合我。虽然我真正想做的是: p = points[0][0] p['a'] = np.array([1, 1, 1]) 如有必要,还可以对 p 进行其他操作。
    • @Tim:AFAIK,首先指定命名列似乎很自然,然后才使用数字索引。因此,编写 points['a'][0] 或 points[0]['a'] (适用于 POD 的 dtype 数组)的能力对我来说就像是一顿免费的午餐。
    【解决方案2】:

    有很多方法可以分配积分,如果您希望您的方法有效:

    points[0][0]['a'][:] = np.array([1, 1, 1])
    

    或:

    points[0,0]['a'][:] = np.array([1, 1, 1])
    

    因为points[0,0]['a']是一个数组,如果你想改变数组的内容,你应该使用索引。

    【讨论】:

      猜你喜欢
      • 2023-04-11
      • 2012-10-23
      • 2014-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      相关资源
      最近更新 更多