Copy a flat numpy array to an given attribute of an np.array of objects
<p>Can I copy a 1D numpy array to an given attribute of an np.array of objects without using a for loop?
For filling the "percentage" property of all PlotInputGridData objects in objarray with the "dist" array, i use something like this:</p>

<pre><code>import numpy as np

class PlotInputGridData(object):
    def __init__(self):
        self.rangemin = 0
        self.rangemax = 0
        self.rangelabel = ''
        self.percentage = 0
        self.number = 0

objarray = np.arange(6, dtype=PlotInputGridData)
for i in range(objarray.size):
    t = PlotInputGridData()
    objarray[i] = t

dist = np.array([52, 26, 12, 6, 3, 1], dtype=np.int)

for i in range(dist.size):
    objarray[i].percentage = dist[i]
</code></pre>

<p>i need to do</p>

<ul>
<li>objarray[0].percentage= dist[0]   </li>
<li>objarray[1].percentage= dist[1] </li>
<li>... and so on</li>
</ul>

<p>is there any way of copying dist[] to objarray[].percentage in a more concise way without the for loop on the last 2 lines? </p>

<p>I don't think there is a way to do that assignment without a for-loop.</p>

<p>You could do it if you used a <a href="http://docs.scipy.org/doc/numpy/user/basics.rec.html" rel="nofollow">structured array</a> instead of an array of objects.  The class <code>PlotInputGridData</code> is just a few fields, so the data it holds is easily represented as a structured data type instead of a Python class.</p>

<p>For example,</p>

<pre><code>In [15]: grid_data_type = np.dtype([('rangemin', float),
    ...:                            ('rangemax', float),
    ...:                            ('rangelabel', 'S16'),
    ...:                            ('percentage', float),
    ...:                            ('number', int)])
</code></pre>

<p><code>grid_data_type</code> is a structured data type with five fields.  (Change the types of the individual fields as needed.)  This data type can be used as the <code>dtype</code> of a numpy array:</p>

<pre><code>In [16]: a = np.zeros(6, dtype=grid_data_dtype)

In [17]: dist = np.array([52, 26, 12, 6, 3, 1])
</code></pre>

<p>The following assigns the array <code>dist</code> to the <code>'percentage'</code> field:</p>

<pre><code>In [18]: a['percentage'] = dist
</code></pre>

<p>Take a look at <code>a</code>:</p>

<pre><code>In [19]: a
Out[19]: 
array([(0.0, 0.0, b'', 52.0, 0), (0.0, 0.0, b'', 26.0, 0),
       (0.0, 0.0, b'', 12.0, 0), (0.0, 0.0, b'', 6.0, 0),
       (0.0, 0.0, b'', 3.0, 0), (0.0, 0.0, b'', 1.0, 0)], 
      dtype=[('rangemin', '&lt;f8'), ('rangemax', '&lt;f8'), ('rangelabel', 'S16'), ('percentage', '&lt;f8'), ('number', '&lt;i8')])

In [20]: a[0]
Out[20]: (0.0, 0.0, b'', 52.0, 0)

In [21]: a['percentage']
Out[21]: array([ 52.,  26.,  12.,   6.,   3.,   1.])
</code></pre>

python arrays numpy