1

I'm trying to make a an array of mixed types with an int and string, but am getting an error when populating the string.

a = np.full(2, np.nan, dtype='u4,S10'
a[0] = 1
a[1] = b'abc'

And that gives me the error

ValueError: invalid literal for int() with base 10: b'abc'

Is there a way to have an array of mixed types that I can put byte arrays into like this?

TheStrangeQuark
  • 2,257
  • 5
  • 31
  • 58

2 Answers2

0

You are trying to assign to a whole row.

Try:

a = np.full(2, np.nan, dtype='u4, S10')
a[0][0] = 1
a[0][1] = 'abc'
Learning is a mess
  • 7,479
  • 7
  • 35
  • 71
0
In [246]: a = np.full(2, np.nan, dtype='u4,S10')       

Look at the resulting array. Note the () making the 2 records. Also note that np.nan (a float) has been converted to other values according to the specified dtype (e.g. string 'nan'):

In [247]: a                                                                                          
Out[247]: array([(0, b'nan'), (0, b'nan')], dtype=[('f0', '<u4'), ('f1', 'S10')])

Assigning 1 - modifying both elements of the 1st record. Again, note the string assignment:

In [248]: a[0] = 1                                                                                   
In [249]: a                                                                                          
Out[249]: array([(1, b'1'), (0, b'nan')], dtype=[('f0', '<u4'), ('f1', 'S10')])

Access by field name:

In [250]: a['f0']                                                                                    
Out[250]: array([1, 0], dtype=uint32)
In [251]: a['f1']                                                                                    
Out[251]: array([b'1', b'nan'], dtype='|S10')

Modifying an element of the string field:

In [252]: a['f1'][1] = b'abc'                                                                        
In [253]: a                                                                                          
Out[253]: array([(1, b'1'), (0, b'abc')], dtype=[('f0', '<u4'), ('f1', 'S10')])

Modifying both elements of a record - with a tuple:

In [254]: a[0] = (23, b'foobar')                                                                     
In [255]: a                                                                                          
Out[255]: 
array([(23, b'foobar'), ( 0, b'abc')],
      dtype=[('f0', '<u4'), ('f1', 'S10')])

Initializing a structured array with a list of tuples:

In [256]: b = np.array([(2,b'xxx'),(34,b'xyz')], dtype=a.dtype)                                      
In [257]: b                                                                                          
Out[257]: array([( 2, b'xxx'), (34, b'xyz')], dtype=[('f0', '<u4'), ('f1', 'S10')])

All of this is documented:

https://docs.scipy.org/doc/numpy/user/basics.rec.html#assigning-data-to-a-structured-array

hpaulj
  • 221,503
  • 14
  • 230
  • 353