structured_arrays.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. """
  2. =================
  3. Structured Arrays
  4. =================
  5. Introduction
  6. ============
  7. Structured arrays are ndarrays whose datatype is a composition of simpler
  8. datatypes organized as a sequence of named :term:`fields <field>`. For example,
  9. ::
  10. >>> x = np.array([('Rex', 9, 81.0), ('Fido', 3, 27.0)],
  11. ... dtype=[('name', 'U10'), ('age', 'i4'), ('weight', 'f4')])
  12. >>> x
  13. array([('Rex', 9, 81.0), ('Fido', 3, 27.0)],
  14. dtype=[('name', 'S10'), ('age', '<i4'), ('weight', '<f4')])
  15. Here ``x`` is a one-dimensional array of length two whose datatype is a
  16. structure with three fields: 1. A string of length 10 or less named 'name', 2.
  17. a 32-bit integer named 'age', and 3. a 32-bit float named 'weight'.
  18. If you index ``x`` at position 1 you get a structure::
  19. >>> x[1]
  20. ('Fido', 3, 27.0)
  21. You can access and modify individual fields of a structured array by indexing
  22. with the field name::
  23. >>> x['age']
  24. array([9, 3], dtype=int32)
  25. >>> x['age'] = 5
  26. >>> x
  27. array([('Rex', 5, 81.0), ('Fido', 5, 27.0)],
  28. dtype=[('name', 'S10'), ('age', '<i4'), ('weight', '<f4')])
  29. Structured datatypes are designed to be able to mimic 'structs' in the C
  30. language, and share a similar memory layout. They are meant for interfacing with
  31. C code and for low-level manipulation of structured buffers, for example for
  32. interpreting binary blobs. For these purposes they support specialized features
  33. such as subarrays, nested datatypes, and unions, and allow control over the
  34. memory layout of the structure.
  35. Users looking to manipulate tabular data, such as stored in csv files, may find
  36. other pydata projects more suitable, such as xarray, pandas, or DataArray.
  37. These provide a high-level interface for tabular data analysis and are better
  38. optimized for that use. For instance, the C-struct-like memory layout of
  39. structured arrays in numpy can lead to poor cache behavior in comparison.
  40. .. _defining-structured-types:
  41. Structured Datatypes
  42. ====================
  43. A structured datatype can be thought of as a sequence of bytes of a certain
  44. length (the structure's :term:`itemsize`) which is interpreted as a collection
  45. of fields. Each field has a name, a datatype, and a byte offset within the
  46. structure. The datatype of a field may be any numpy datatype including other
  47. structured datatypes, and it may also be a :term:`sub-array` which behaves like
  48. an ndarray of a specified shape. The offsets of the fields are arbitrary, and
  49. fields may even overlap. These offsets are usually determined automatically by
  50. numpy, but can also be specified.
  51. Structured Datatype Creation
  52. ----------------------------
  53. Structured datatypes may be created using the function :func:`numpy.dtype`.
  54. There are 4 alternative forms of specification which vary in flexibility and
  55. conciseness. These are further documented in the
  56. :ref:`Data Type Objects <arrays.dtypes.constructing>` reference page, and in
  57. summary they are:
  58. 1. A list of tuples, one tuple per field
  59. Each tuple has the form ``(fieldname, datatype, shape)`` where shape is
  60. optional. ``fieldname`` is a string (or tuple if titles are used, see
  61. :ref:`Field Titles <titles>` below), ``datatype`` may be any object
  62. convertible to a datatype, and ``shape`` is a tuple of integers specifying
  63. subarray shape.
  64. >>> np.dtype([('x', 'f4'), ('y', np.float32), ('z', 'f4', (2,2))])
  65. dtype=[('x', '<f4'), ('y', '<f4'), ('z', '<f4', (2, 2))])
  66. If ``fieldname`` is the empty string ``''``, the field will be given a
  67. default name of the form ``f#``, where ``#`` is the integer index of the
  68. field, counting from 0 from the left::
  69. >>> np.dtype([('x', 'f4'),('', 'i4'),('z', 'i8')])
  70. dtype([('x', '<f4'), ('f1', '<i4'), ('z', '<i8')])
  71. The byte offsets of the fields within the structure and the total
  72. structure itemsize are determined automatically.
  73. 2. A string of comma-separated dtype specifications
  74. In this shorthand notation any of the :ref:`string dtype specifications
  75. <arrays.dtypes.constructing>` may be used in a string and separated by
  76. commas. The itemsize and byte offsets of the fields are determined
  77. automatically, and the field names are given the default names ``f0``,
  78. ``f1``, etc. ::
  79. >>> np.dtype('i8,f4,S3')
  80. dtype([('f0', '<i8'), ('f1', '<f4'), ('f2', 'S3')])
  81. >>> np.dtype('3int8, float32, (2,3)float64')
  82. dtype([('f0', 'i1', 3), ('f1', '<f4'), ('f2', '<f8', (2, 3))])
  83. 3. A dictionary of field parameter arrays
  84. This is the most flexible form of specification since it allows control
  85. over the byte-offsets of the fields and the itemsize of the structure.
  86. The dictionary has two required keys, 'names' and 'formats', and four
  87. optional keys, 'offsets', 'itemsize', 'aligned' and 'titles'. The values
  88. for 'names' and 'formats' should respectively be a list of field names and
  89. a list of dtype specifications, of the same length. The optional 'offsets'
  90. value should be a list of integer byte-offsets, one for each field within
  91. the structure. If 'offsets' is not given the offsets are determined
  92. automatically. The optional 'itemsize' value should be an integer
  93. describing the total size in bytes of the dtype, which must be large
  94. enough to contain all the fields.
  95. ::
  96. >>> np.dtype({'names': ['col1', 'col2'], 'formats': ['i4','f4']})
  97. dtype([('col1', '<i4'), ('col2', '<f4')])
  98. >>> np.dtype({'names': ['col1', 'col2'],
  99. ... 'formats': ['i4','f4'],
  100. ... 'offsets': [0, 4],
  101. ... 'itemsize': 12})
  102. dtype({'names':['col1','col2'], 'formats':['<i4','<f4'], 'offsets':[0,4], 'itemsize':12})
  103. Offsets may be chosen such that the fields overlap, though this will mean
  104. that assigning to one field may clobber any overlapping field's data. As
  105. an exception, fields of :class:`numpy.object` type cannot overlap with
  106. other fields, because of the risk of clobbering the internal object
  107. pointer and then dereferencing it.
  108. The optional 'aligned' value can be set to ``True`` to make the automatic
  109. offset computation use aligned offsets (see :ref:`offsets-and-alignment`),
  110. as if the 'align' keyword argument of :func:`numpy.dtype` had been set to
  111. True.
  112. The optional 'titles' value should be a list of titles of the same length
  113. as 'names', see :ref:`Field Titles <titles>` below.
  114. 4. A dictionary of field names
  115. The use of this form of specification is discouraged, but documented here
  116. because older numpy code may use it. The keys of the dictionary are the
  117. field names and the values are tuples specifying type and offset::
  118. >>> np.dtype=({'col1': ('i1',0), 'col2': ('f4',1)})
  119. dtype([(('col1'), 'i1'), (('col2'), '>f4')])
  120. This form is discouraged because Python dictionaries do not preserve order
  121. in Python versions before Python 3.6, and the order of the fields in a
  122. structured dtype has meaning. :ref:`Field Titles <titles>` may be
  123. specified by using a 3-tuple, see below.
  124. Manipulating and Displaying Structured Datatypes
  125. ------------------------------------------------
  126. The list of field names of a structured datatype can be found in the ``names``
  127. attribute of the dtype object::
  128. >>> d = np.dtype([('x', 'i8'), ('y', 'f4')])
  129. >>> d.names
  130. ('x', 'y')
  131. The field names may be modified by assigning to the ``names`` attribute using a
  132. sequence of strings of the same length.
  133. The dtype object also has a dictionary-like attribute, ``fields``, whose keys
  134. are the field names (and :ref:`Field Titles <titles>`, see below) and whose
  135. values are tuples containing the dtype and byte offset of each field. ::
  136. >>> d.fields
  137. mappingproxy({'x': (dtype('int64'), 0), 'y': (dtype('float32'), 8)})
  138. Both the ``names`` and ``fields`` attributes will equal ``None`` for
  139. unstructured arrays. The recommended way to test if a dtype is structured is
  140. with `if dt.names is not None` rather than `if dt.names`, to account for dtypes
  141. with 0 fields.
  142. The string representation of a structured datatype is shown in the "list of
  143. tuples" form if possible, otherwise numpy falls back to using the more general
  144. dictionary form.
  145. .. _offsets-and-alignment:
  146. Automatic Byte Offsets and Alignment
  147. ------------------------------------
  148. Numpy uses one of two methods to automatically determine the field byte offsets
  149. and the overall itemsize of a structured datatype, depending on whether
  150. ``align=True`` was specified as a keyword argument to :func:`numpy.dtype`.
  151. By default (``align=False``), numpy will pack the fields together such that
  152. each field starts at the byte offset the previous field ended, and the fields
  153. are contiguous in memory. ::
  154. >>> def print_offsets(d):
  155. ... print("offsets:", [d.fields[name][1] for name in d.names])
  156. ... print("itemsize:", d.itemsize)
  157. >>> print_offsets(np.dtype('u1,u1,i4,u1,i8,u2'))
  158. offsets: [0, 1, 2, 6, 7, 15]
  159. itemsize: 17
  160. If ``align=True`` is set, numpy will pad the structure in the same way many C
  161. compilers would pad a C-struct. Aligned structures can give a performance
  162. improvement in some cases, at the cost of increased datatype size. Padding
  163. bytes are inserted between fields such that each field's byte offset will be a
  164. multiple of that field's alignment, which is usually equal to the field's size
  165. in bytes for simple datatypes, see :c:member:`PyArray_Descr.alignment`. The
  166. structure will also have trailing padding added so that its itemsize is a
  167. multiple of the largest field's alignment. ::
  168. >>> print_offsets(np.dtype('u1,u1,i4,u1,i8,u2', align=True))
  169. offsets: [0, 1, 4, 8, 16, 24]
  170. itemsize: 32
  171. Note that although almost all modern C compilers pad in this way by default,
  172. padding in C structs is C-implementation-dependent so this memory layout is not
  173. guaranteed to exactly match that of a corresponding struct in a C program. Some
  174. work may be needed, either on the numpy side or the C side, to obtain exact
  175. correspondence.
  176. If offsets were specified using the optional ``offsets`` key in the
  177. dictionary-based dtype specification, setting ``align=True`` will check that
  178. each field's offset is a multiple of its size and that the itemsize is a
  179. multiple of the largest field size, and raise an exception if not.
  180. If the offsets of the fields and itemsize of a structured array satisfy the
  181. alignment conditions, the array will have the ``ALIGNED`` :ref:`flag
  182. <numpy.ndarray.flags>` set.
  183. A convenience function :func:`numpy.lib.recfunctions.repack_fields` converts an
  184. aligned dtype or array to a packed one and vice versa. It takes either a dtype
  185. or structured ndarray as an argument, and returns a copy with fields re-packed,
  186. with or without padding bytes.
  187. .. _titles:
  188. Field Titles
  189. ------------
  190. In addition to field names, fields may also have an associated :term:`title`,
  191. an alternate name, which is sometimes used as an additional description or
  192. alias for the field. The title may be used to index an array, just like a
  193. field name.
  194. To add titles when using the list-of-tuples form of dtype specification, the
  195. field name may be specified as a tuple of two strings instead of a single
  196. string, which will be the field's title and field name respectively. For
  197. example::
  198. >>> np.dtype([(('my title', 'name'), 'f4')])
  199. When using the first form of dictionary-based specification, the titles may be
  200. supplied as an extra ``'titles'`` key as described above. When using the second
  201. (discouraged) dictionary-based specification, the title can be supplied by
  202. providing a 3-element tuple ``(datatype, offset, title)`` instead of the usual
  203. 2-element tuple::
  204. >>> np.dtype({'name': ('i4', 0, 'my title')})
  205. The ``dtype.fields`` dictionary will contain :term:`titles` as keys, if any
  206. titles are used. This means effectively that a field with a title will be
  207. represented twice in the fields dictionary. The tuple values for these fields
  208. will also have a third element, the field title. Because of this, and because
  209. the ``names`` attribute preserves the field order while the ``fields``
  210. attribute may not, it is recommended to iterate through the fields of a dtype
  211. using the ``names`` attribute of the dtype, which will not list titles, as
  212. in::
  213. >>> for name in d.names:
  214. ... print(d.fields[name][:2])
  215. Union types
  216. -----------
  217. Structured datatypes are implemented in numpy to have base type
  218. :class:`numpy.void` by default, but it is possible to interpret other numpy
  219. types as structured types using the ``(base_dtype, dtype)`` form of dtype
  220. specification described in
  221. :ref:`Data Type Objects <arrays.dtypes.constructing>`. Here, ``base_dtype`` is
  222. the desired underlying dtype, and fields and flags will be copied from
  223. ``dtype``. This dtype is similar to a 'union' in C.
  224. Indexing and Assignment to Structured arrays
  225. ============================================
  226. Assigning data to a Structured Array
  227. ------------------------------------
  228. There are a number of ways to assign values to a structured array: Using python
  229. tuples, using scalar values, or using other structured arrays.
  230. Assignment from Python Native Types (Tuples)
  231. ````````````````````````````````````````````
  232. The simplest way to assign values to a structured array is using python tuples.
  233. Each assigned value should be a tuple of length equal to the number of fields
  234. in the array, and not a list or array as these will trigger numpy's
  235. broadcasting rules. The tuple's elements are assigned to the successive fields
  236. of the array, from left to right::
  237. >>> x = np.array([(1,2,3),(4,5,6)], dtype='i8,f4,f8')
  238. >>> x[1] = (7,8,9)
  239. >>> x
  240. array([(1, 2., 3.), (7, 8., 9.)],
  241. dtype=[('f0', '<i8'), ('f1', '<f4'), ('f2', '<f8')])
  242. Assignment from Scalars
  243. ```````````````````````
  244. A scalar assigned to a structured element will be assigned to all fields. This
  245. happens when a scalar is assigned to a structured array, or when an
  246. unstructured array is assigned to a structured array::
  247. >>> x = np.zeros(2, dtype='i8,f4,?,S1')
  248. >>> x[:] = 3
  249. >>> x
  250. array([(3, 3.0, True, b'3'), (3, 3.0, True, b'3')],
  251. dtype=[('f0', '<i8'), ('f1', '<f4'), ('f2', '?'), ('f3', 'S1')])
  252. >>> x[:] = np.arange(2)
  253. >>> x
  254. array([(0, 0.0, False, b'0'), (1, 1.0, True, b'1')],
  255. dtype=[('f0', '<i8'), ('f1', '<f4'), ('f2', '?'), ('f3', 'S1')])
  256. Structured arrays can also be assigned to unstructured arrays, but only if the
  257. structured datatype has just a single field::
  258. >>> twofield = np.zeros(2, dtype=[('A', 'i4'), ('B', 'i4')])
  259. >>> onefield = np.zeros(2, dtype=[('A', 'i4')])
  260. >>> nostruct = np.zeros(2, dtype='i4')
  261. >>> nostruct[:] = twofield
  262. Traceback (most recent call last):
  263. ...
  264. TypeError: Cannot cast scalar from dtype([('A', '<i4'), ('B', '<i4')]) to dtype('int32') according to the rule 'unsafe'
  265. Assignment from other Structured Arrays
  266. ```````````````````````````````````````
  267. Assignment between two structured arrays occurs as if the source elements had
  268. been converted to tuples and then assigned to the destination elements. That
  269. is, the first field of the source array is assigned to the first field of the
  270. destination array, and the second field likewise, and so on, regardless of
  271. field names. Structured arrays with a different number of fields cannot be
  272. assigned to each other. Bytes of the destination structure which are not
  273. included in any of the fields are unaffected. ::
  274. >>> a = np.zeros(3, dtype=[('a', 'i8'), ('b', 'f4'), ('c', 'S3')])
  275. >>> b = np.ones(3, dtype=[('x', 'f4'), ('y', 'S3'), ('z', 'O')])
  276. >>> b[:] = a
  277. >>> b
  278. array([(0.0, b'0.0', b''), (0.0, b'0.0', b''), (0.0, b'0.0', b'')],
  279. dtype=[('x', '<f4'), ('y', 'S3'), ('z', 'O')])
  280. Assignment involving subarrays
  281. ``````````````````````````````
  282. When assigning to fields which are subarrays, the assigned value will first be
  283. broadcast to the shape of the subarray.
  284. Indexing Structured Arrays
  285. --------------------------
  286. Accessing Individual Fields
  287. ```````````````````````````
  288. Individual fields of a structured array may be accessed and modified by indexing
  289. the array with the field name. ::
  290. >>> x = np.array([(1,2),(3,4)], dtype=[('foo', 'i8'), ('bar', 'f4')])
  291. >>> x['foo']
  292. array([1, 3])
  293. >>> x['foo'] = 10
  294. >>> x
  295. array([(10, 2.), (10, 4.)],
  296. dtype=[('foo', '<i8'), ('bar', '<f4')])
  297. The resulting array is a view into the original array. It shares the same
  298. memory locations and writing to the view will modify the original array. ::
  299. >>> y = x['bar']
  300. >>> y[:] = 10
  301. >>> x
  302. array([(10, 5.), (10, 5.)],
  303. dtype=[('foo', '<i8'), ('bar', '<f4')])
  304. This view has the same dtype and itemsize as the indexed field, so it is
  305. typically a non-structured array, except in the case of nested structures.
  306. >>> y.dtype, y.shape, y.strides
  307. (dtype('float32'), (2,), (12,))
  308. If the accessed field is a subarray, the dimensions of the subarray
  309. are appended to the shape of the result::
  310. >>> x = np.zeros((2,2), dtype=[('a', np.int32), ('b', np.float64, (3,3))])
  311. >>> x['a'].shape
  312. (2, 2)
  313. >>> x['b'].shape
  314. (2, 2, 3, 3)
  315. Accessing Multiple Fields
  316. ```````````````````````````
  317. One can index and assign to a structured array with a multi-field index, where
  318. the index is a list of field names.
  319. .. warning::
  320. The behavior of multi-field indexes changed from Numpy 1.15 to Numpy 1.16.
  321. The result of indexing with a multi-field index is a view into the original
  322. array, as follows::
  323. >>> a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'i4'), ('c', 'f4')])
  324. >>> a[['a', 'c']]
  325. array([(0, 0.), (0, 0.), (0, 0.)],
  326. dtype={'names':['a','c'], 'formats':['<i4','<f4'], 'offsets':[0,8], 'itemsize':12})
  327. Assignment to the view modifies the original array. The view's fields will be
  328. in the order they were indexed. Note that unlike for single-field indexing, the
  329. view's dtype has the same itemsize as the original array, and has fields at the
  330. same offsets as in the original array, and unindexed fields are merely missing.
  331. .. warning::
  332. In Numpy 1.15, indexing an array with a multi-field index returned a copy of
  333. the result above, but with fields packed together in memory as if
  334. passed through :func:`numpy.lib.recfunctions.repack_fields`.
  335. The new behavior as of Numpy 1.16 leads to extra "padding" bytes at the
  336. location of unindexed fields compared to 1.15. You will need to update any
  337. code which depends on the data having a "packed" layout. For instance code
  338. such as::
  339. >>> a = np.zeros(3, dtype=[('a', 'i4'), ('b', 'i4'), ('c', 'f4')])
  340. >>> a[['a','c']].view('i8') # Fails in Numpy 1.16
  341. ValueError: When changing to a smaller dtype, its size must be a divisor of the size of original dtype
  342. will need to be changed. This code has raised a ``FutureWarning`` since
  343. Numpy 1.12, and similar code has raised ``FutureWarning`` since 1.7.
  344. In 1.16 a number of functions have been introduced in the
  345. :module:`numpy.lib.recfunctions` module to help users account for this
  346. change. These are
  347. :func:`numpy.lib.recfunctions.repack_fields`.
  348. :func:`numpy.lib.recfunctions.structured_to_unstructured`,
  349. :func:`numpy.lib.recfunctions.unstructured_to_structured`,
  350. :func:`numpy.lib.recfunctions.apply_along_fields`,
  351. :func:`numpy.lib.recfunctions.assign_fields_by_name`, and
  352. :func:`numpy.lib.recfunctions.require_fields`.
  353. The function :func:`numpy.lib.recfunctions.repack_fields` can always be
  354. used to reproduce the old behavior, as it will return a packed copy of the
  355. structured array. The code above, for example, can be replaced with:
  356. >>> repack_fields(a[['a','c']]).view('i8') # supported in 1.16
  357. array([0, 0, 0])
  358. Furthermore, numpy now provides a new function
  359. :func:`numpy.lib.recfunctions.structured_to_unstructured` which is a safer
  360. and more efficient alternative for users who wish to convert structured
  361. arrays to unstructured arrays, as the view above is often indeded to do.
  362. This function allows safe conversion to an unstructured type taking into
  363. account padding, often avoids a copy, and also casts the datatypes
  364. as needed, unlike the view. Code such as:
  365. >>> a = np.zeros(3, dtype=[('x', 'f4'), ('y', 'f4'), ('z', 'f4')])
  366. >>> a[['x', 'z']].view('f4')
  367. can be made safer by replacing with:
  368. >>> structured_to_unstructured(a[['x', 'z']])
  369. array([0, 0, 0])
  370. Assignment to an array with a multi-field index modifies the original array::
  371. >>> a[['a', 'c']] = (2, 3)
  372. >>> a
  373. array([(2, 0, 3.0), (2, 0, 3.0), (2, 0, 3.0)],
  374. dtype=[('a', '<i8'), ('b', '<i4'), ('c', '<f8')])
  375. This obeys the structured array assignment rules described above. For example,
  376. this means that one can swap the values of two fields using appropriate
  377. multi-field indexes::
  378. >>> a[['a', 'c']] = a[['c', 'a']]
  379. Indexing with an Integer to get a Structured Scalar
  380. ```````````````````````````````````````````````````
  381. Indexing a single element of a structured array (with an integer index) returns
  382. a structured scalar::
  383. >>> x = np.array([(1, 2., 3.)], dtype='i,f,f')
  384. >>> scalar = x[0]
  385. >>> scalar
  386. (1, 2., 3.)
  387. >>> type(scalar)
  388. numpy.void
  389. Unlike other numpy scalars, structured scalars are mutable and act like views
  390. into the original array, such that modifying the scalar will modify the
  391. original array. Structured scalars also support access and assignment by field
  392. name::
  393. >>> x = np.array([(1,2),(3,4)], dtype=[('foo', 'i8'), ('bar', 'f4')])
  394. >>> s = x[0]
  395. >>> s['bar'] = 100
  396. >>> x
  397. array([(1, 100.), (3, 4.)],
  398. dtype=[('foo', '<i8'), ('bar', '<f4')])
  399. Similarly to tuples, structured scalars can also be indexed with an integer::
  400. >>> scalar = np.array([(1, 2., 3.)], dtype='i,f,f')[0]
  401. >>> scalar[0]
  402. 1
  403. >>> scalar[1] = 4
  404. Thus, tuples might be thought of as the native Python equivalent to numpy's
  405. structured types, much like native python integers are the equivalent to
  406. numpy's integer types. Structured scalars may be converted to a tuple by
  407. calling :func:`ndarray.item`::
  408. >>> scalar.item(), type(scalar.item())
  409. ((1, 2.0, 3.0), tuple)
  410. Viewing Structured Arrays Containing Objects
  411. --------------------------------------------
  412. In order to prevent clobbering object pointers in fields of
  413. :class:`numpy.object` type, numpy currently does not allow views of structured
  414. arrays containing objects.
  415. Structure Comparison
  416. --------------------
  417. If the dtypes of two void structured arrays are equal, testing the equality of
  418. the arrays will result in a boolean array with the dimensions of the original
  419. arrays, with elements set to ``True`` where all fields of the corresponding
  420. structures are equal. Structured dtypes are equal if the field names,
  421. dtypes and titles are the same, ignoring endianness, and the fields are in
  422. the same order::
  423. >>> a = np.zeros(2, dtype=[('a', 'i4'), ('b', 'i4')])
  424. >>> b = np.ones(2, dtype=[('a', 'i4'), ('b', 'i4')])
  425. >>> a == b
  426. array([False, False])
  427. Currently, if the dtypes of two void structured arrays are not equivalent the
  428. comparison fails, returning the scalar value ``False``. This behavior is
  429. deprecated as of numpy 1.10 and will raise an error or perform elementwise
  430. comparison in the future.
  431. The ``<`` and ``>`` operators always return ``False`` when comparing void
  432. structured arrays, and arithmetic and bitwise operations are not supported.
  433. Record Arrays
  434. =============
  435. As an optional convenience numpy provides an ndarray subclass,
  436. :class:`numpy.recarray`, and associated helper functions in the
  437. :mod:`numpy.rec` submodule, that allows access to fields of structured arrays
  438. by attribute instead of only by index. Record arrays also use a special
  439. datatype, :class:`numpy.record`, that allows field access by attribute on the
  440. structured scalars obtained from the array.
  441. The simplest way to create a record array is with :func:`numpy.rec.array`::
  442. >>> recordarr = np.rec.array([(1,2.,'Hello'),(2,3.,"World")],
  443. ... dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'S10')])
  444. >>> recordarr.bar
  445. array([ 2., 3.], dtype=float32)
  446. >>> recordarr[1:2]
  447. rec.array([(2, 3.0, 'World')],
  448. dtype=[('foo', '<i4'), ('bar', '<f4'), ('baz', 'S10')])
  449. >>> recordarr[1:2].foo
  450. array([2], dtype=int32)
  451. >>> recordarr.foo[1:2]
  452. array([2], dtype=int32)
  453. >>> recordarr[1].baz
  454. 'World'
  455. :func:`numpy.rec.array` can convert a wide variety of arguments into record
  456. arrays, including structured arrays::
  457. >>> arr = array([(1,2.,'Hello'),(2,3.,"World")],
  458. ... dtype=[('foo', 'i4'), ('bar', 'f4'), ('baz', 'S10')])
  459. >>> recordarr = np.rec.array(arr)
  460. The :mod:`numpy.rec` module provides a number of other convenience functions for
  461. creating record arrays, see :ref:`record array creation routines
  462. <routines.array-creation.rec>`.
  463. A record array representation of a structured array can be obtained using the
  464. appropriate :ref:`view`::
  465. >>> arr = np.array([(1,2.,'Hello'),(2,3.,"World")],
  466. ... dtype=[('foo', 'i4'),('bar', 'f4'), ('baz', 'a10')])
  467. >>> recordarr = arr.view(dtype=dtype((np.record, arr.dtype)),
  468. ... type=np.recarray)
  469. For convenience, viewing an ndarray as type :class:`np.recarray` will
  470. automatically convert to :class:`np.record` datatype, so the dtype can be left
  471. out of the view::
  472. >>> recordarr = arr.view(np.recarray)
  473. >>> recordarr.dtype
  474. dtype((numpy.record, [('foo', '<i4'), ('bar', '<f4'), ('baz', 'S10')]))
  475. To get back to a plain ndarray both the dtype and type must be reset. The
  476. following view does so, taking into account the unusual case that the
  477. recordarr was not a structured type::
  478. >>> arr2 = recordarr.view(recordarr.dtype.fields or recordarr.dtype, np.ndarray)
  479. Record array fields accessed by index or by attribute are returned as a record
  480. array if the field has a structured type but as a plain ndarray otherwise. ::
  481. >>> recordarr = np.rec.array([('Hello', (1,2)),("World", (3,4))],
  482. ... dtype=[('foo', 'S6'),('bar', [('A', int), ('B', int)])])
  483. >>> type(recordarr.foo)
  484. <type 'numpy.ndarray'>
  485. >>> type(recordarr.bar)
  486. <class 'numpy.core.records.recarray'>
  487. Note that if a field has the same name as an ndarray attribute, the ndarray
  488. attribute takes precedence. Such fields will be inaccessible by attribute but
  489. will still be accessible by index.
  490. """
  491. from __future__ import division, absolute_import, print_function