2011-08-28 53 views
6

我發現與NumPy的一個ndarray以下令人費解的行爲和一個自定義的D型細胞,當數組賦值問題:NumPy的:使用自定義的D型

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]。 0. 0],只在第一個座標上執行賦值。我可以通過座標明智地執行分配來解決這個問題,但這看起來沒有必要,因爲在這種情況下完全分配肯定應該是默認行爲。

想到這裏發生了什麼?

回答

2

有分配的點數多的方法,如果你希望你的方法工作:

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

或:

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

因爲點[0,0] [ '一']是一個數組,如果你想改變數組的內容,你應該使用索引。

+0

正是我在找的,謝謝。 –

3

如果您更改索引的排序,如下所示:points['a'][0][0] = np.array([1, 1, 1]),它對我來說可行(在Ubuntu 10.04上,python 2.6.5,numpy 1.3.0)。我希望我知道爲什麼。

+0

也適用於我。雖然我真的想做的事情會是這樣的: p = points [0] [0] p ['a'] = np.array([1,1,1]) 和其他操作如果有必要的話。 –

+0

@Tim:AFAIK,首先指定命名列似乎很自然,然後纔去數字索引。因此,寫作點['a'] [0]或點[0] ['a'](適用於dtype-ed POD陣列)的能力就像是免費的午餐。 –