Defining columns in numpy array - TypeError: invalid type promotion
<p>I am defining an array which should look like this </p>

<pre><code>['word1', 2000, 21]
['word2', 2002, 33]
['word3', 1988, 51]
['word4', 1999, 26]
['word5', 2001, 72]
</code></pre>

<p>However when I append an a new entry I get a TypeError. </p>

<pre><code>import numpy as np

npdtype = [('word', 'S35'), ('year', int), ('wordcount', int)]
np_array = np.empty((0,3), dtype=npdtype)

word = 'word1'
year = '2001'
word_count = '21'

np_array = np.append(np_array, [['word1', int(year), int(word_count)]], axis=0)
</code></pre>

<p>Traceback </p>

<pre><code> File "/home/matt/.local/lib/python2.7/site-packages/numpy/lib/function_base.py", line 4586, in append
return concatenate((arr, values), axis=axis)
 TypeError: invalid type promotion
</code></pre>

<p>What am I doing wrong?</p>

<p>Thanks</p>

<p>Follow @hpaulj's advice and then tidy up.</p>

<pre><code>import numpy as np

npdtype = [('word', 'S35'), ('year', np.int16), ('wordcount', np.int16)]
np_array = np.empty((0,3), dtype=npdtype)

word = 'word1'
year = '2001'
word_count = '21'

column = np.array( [b'word1', np.int16(year), np.int16(word_count)], dtype=npdtype)
print (column.shape)
column.shape=-1,3
print (column.shape)
print (column)
result=np.concatenate((np_array,column),axis=0)
print (result)

#~ np_array = np.append(np_array, [['word1', int(year), int(word_count)]], axis=0)
</code></pre>

<p>The two things that I found:</p>

<ul>
<li>Meticulous matching of the types of record items is required, hence the use of numpy types in the definition of npdtype and conversions of strings; and also use of <strong>b</strong> prefix to the first element of the record.</li>
<li>The created column has a curious shape, thus the need to reshape it.</li>
</ul>

<p>Here's the output.</p>

<pre><code>&gt;pythonw -u "temp.py"
(3,)
(1, 3)
[[(b'word1', 0, 0) (b'\xd1\x07', 0, 0) (b'\x15', 0, 0)]]
[[(b'word1', 0, 0) (b'\xd1\x07', 0, 0) (b'\x15', 0, 0)]]
&gt;Exit code: 0
</code></pre>

python numpy