how to create empty numpy array to store different kinds of data
<p>I am trying to start with an empty numpy array. As the code progresses the first column should be filled with <code>datetime.datetime</code>, the second column should be filled with <code>str</code>, the third columns with <code>float</code>, and fourth column with <code>int</code>.</p>

<p>I tried the following:</p>

<pre><code>A = np.empty([10, 4])
A[0][0] = datetime.datetime(2016, 10, 1, 1, 0)
</code></pre>

<p>I get the error:</p>

<pre><code>TypeError: float() argument must be a string or a number
</code></pre>

<p>A structured array approach:</p>

<p>define a dtype according to your column specs:</p>

<pre><code>In [460]: dt=np.dtype('O,U10,f,i')
In [461]: from datetime import datetime
</code></pre>

<p>Initalize an empty array, with 3 elements (not 3x4)</p>

<pre><code>In [462]: A = np.empty((3,), dtype=dt)
In [463]: A
Out[463]: 
array([(None, '', 0.0, 0), (None, '', 0.0, 0), (None, '', 0.0, 0)], 
      dtype=[('f0', 'O'), ('f1', '&lt;U10'), ('f2', '&lt;f4'), ('f3', '&lt;i4')])
</code></pre>

<p>fill in some values - by field name (not column number)</p>

<pre><code>In [464]: A['f1']=['one','two','three']
In [465]: A['f0'][0]=datetime(2016, 10, 1, 1, 0)    
In [467]: A['f2']=np.arange(3)
In [468]: A
Out[468]: 
array([(datetime.datetime(2016, 10, 1, 1, 0), 'one', 0.0, 0),
       (None, 'two', 1.0, 0), 
       (None, 'three', 2.0, 0)], 
      dtype=[('f0', 'O'), ('f1', '&lt;U10'), ('f2', '&lt;f4'), ('f3', '&lt;i4')])
</code></pre>

<p>View on element of this array:</p>

<pre><code>In [469]: A[0]
Out[469]: (datetime.datetime(2016, 10, 1, 1, 0), 'one', 0.0, 0)
</code></pre>

<p>I chose to make the 1st field <code>object</code> dtype, so it can hold a <code>datetime</code> object - which isn't a number or string.</p>

<p><code>np.datetime64</code> stores a date as a float, and provides a lot of functionality that <code>datetime</code> objects don't:</p>

<pre><code>In [484]: dt1=np.dtype('datetime64[s],U10,f,i')
In [485]: A1 = np.empty((3,), dtype=dt1)
In [486]: A1['f0']=datetime(2016, 10, 1, 1, 0)
In [487]: A1['f3']=np.arange(3)
In [488]: A1
Out[488]: 
array([(datetime.datetime(2016, 10, 1, 1, 0), '', 0.0, 0),
       (datetime.datetime(2016, 10, 1, 1, 0), '', 0.0, 1),
       (datetime.datetime(2016, 10, 1, 1, 0), '', 0.0, 2)], 
      dtype=[('f0', '&lt;M8[s]'), ('f1', '&lt;U10'), ('f2', '&lt;f4'), ('f3', '&lt;i4')])
</code></pre>

<p>A third approach is to make the whole array object dtype.  That's effectively a glorified list.  Many operations resort to plain iteration, or just aren't implemented.  It's more general but you loose a lot of the power of normal numeric arrays.</p>

python numpy