[Numpy-discussion] Constant array of tuples
Christopher Barker
Chris.Barker at noaa.gov
Fri Apr 10 19:11:19 EDT 2009
Frank Peacock wrote:
> Hello
>
> I would like to know whether there is a simple way to construct a constant
> array of tuples:
>
> How do I construct an array of size (width*height) where each element is
> (w,x,y,z)
Is this what you want?
a = np.empty((5,6), dtype=np.object)
>>> for i in range(len(a.flat)):
... a.flat[i] = (1,2,3,4)
...
>>> a
array([[(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4),
(1, 2, 3, 4), (1, 2, 3, 4)],
[(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4),
(1, 2, 3, 4), (1, 2, 3, 4)],
[(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4),
(1, 2, 3, 4), (1, 2, 3, 4)],
[(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4),
(1, 2, 3, 4), (1, 2, 3, 4)],
[(1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4), (1, 2, 3, 4),
(1, 2, 3, 4), (1, 2, 3, 4)]], dtype=object)
Interestingly:
>>> a[:,:] = (1,2,3,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: shape mismatch: objects cannot be broadcast to a single shape
Doesn't work - even though (1,2,3,4) is a tuple, which is a single object.
Anyway, I suspect that that's not really what you want, but rather, you
might be looking for:
>>> a = np.zeros((w,h,4), np.float)
>>> a[:,:] = (1,2,3,4)
>>> a
array([[[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.]],
[[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.]],
[[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.],
[ 1., 2., 3., 4.]]])
-Chris
--
Christopher Barker, Ph.D.
Oceanographer
Emergency Response Division
NOAA/NOS/OR&R (206) 526-6959 voice
7600 Sand Point Way NE (206) 526-6329 fax
Seattle, WA 98115 (206) 526-6317 main reception
Chris.Barker at noaa.gov
More information about the NumPy-Discussion
mailing list