Search code examples
pythonarraysnumpydtype

Numpy.array dtype assignment failure


I am entirely new to numpy and am attempting to create a structured array. My inputs are as follows:

data = [2, 0, '1431.033', '436.7573', '170.9705', 0, '', 0]
dt = [('ID', 'int'),
      ('CP', 'int'),
      ('X1', 'float'),
      ('X2', 'float'),
      ('X3', 'float'),
      ('CD', 'int'),
      ('PS', 'str'),
      ('SEID', 'int')]

When I attempt to create the array using np.array(data, dtypes=dt), I get the error {ValueError}invalid literal for int() with base 10: '1431.033'.

What am I doing wrong here?


Solution

  • From the documentation, The simplest way to assign values to a structured array is using python native tuples. By organizing my data as tuple within list, the structured array can be created successfully.

    data = [(2, 0, '1431.033', '436.7573', '170.9705', 0, '', 0)]
    dt = [('ID', 'int'),
          ('CP', 'int'),
          ('X1', 'float'),
          ('X2', 'float'),
          ('X3', 'float'),
          ('CD', 'int'),
          ('PS', 'str'),
          ('SEID', 'int')]