Note that there are some explanatory texts on larger screens.

plurals
  1. POndim of structured arrays in numpy?
    primarykey
    data
    text
    <p>This is similarly worded question as <a href="https://stackoverflow.com/questions/10542263/ndim-in-numpy-array-loaded-with-scipy-io-loadmat">ndim in numpy array loaded with scipy.io.loadmat?</a> - but it's actually a lot more basic. </p> <p>Say I have this structured array:</p> <pre class="lang-python prettyprint-override"><code>import sys import numpy as np from pprint import pprint a = np.array([(1.5,2.5),(3.,4.),(1.,3.)], dtype=[('x','f4'),('y',np.float32)]) pprint(a) # array([(1.5, 2.5), (3.0, 4.0), (1.0, 3.0)], # dtype=[('x', '&lt;f4'), ('y', '&lt;f4')]) </code></pre> <p>I see that as a table of 3 rows and 2 columns, so 3x2. However, trying to use <code>ndim</code> here, I see:</p> <pre class="lang-python prettyprint-override"><code>print(".ndim", a.ndim) print(".shape", a.shape) print("asarray.ndim", np.asarray(a).ndim) # ('.ndim', 1) # ('.shape', (3,)) # ('asarray.ndim', 1) </code></pre> <p>... and this is what puzzles me - what makes <code>numpy</code> think this should be a 1d array, when there are clearly fields/columns defined ?!</p> <p>Given that output, no wonder that reshape doesn't work:</p> <pre class="lang-python prettyprint-override"><code>pprint(a.reshape(3,2)) # ValueError: total size of new array must be unchanged </code></pre> <p>Now, I can bruteforce the structured array into a ("normal" numpy, I guess?) array:</p> <pre class="lang-python prettyprint-override"><code>b = np.column_stack((a['x'], a['y'])) pprint(b) # array([[ 1.5, 2.5], # [ 3. , 4. ], # [ 1. , 3. ]], dtype=float32) print(".ndim", b.ndim) print(".shape", b.shape) print("asarray.ndim", np.asarray(b).ndim) # ('.ndim', 2) # ('.shape', (3, 2)) # ('asarray.ndim', 2) </code></pre> <p>... and so I get the information that I expect. </p> <p>But I am wondering - why does numpy behave like this with structured arrays - and is there a way to retrieve the 3x2 shape information from the original structured array (<code>a</code>) directly, without "casting" to a "normal" array?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload