NumPy array/matrix of mixed types

后端 未结 5 1338
日久生厌
日久生厌 2020-12-07 00:42

I\'m trying to create a NumPy array/matrix (Nx3) with mixed data types (string, integer, integer). But when I\'m appending this matrix by adding some data, I get an error: <

5条回答
  •  遥遥无期
    2020-12-07 01:12

    I think this is what you are trying to accomplish - create an empty array of the desired dtype, and then add one or more data sets to it. The result will have shape (N,), not (N,3).

    As I noted in a comment, np.append uses np.concatenate, so I am using that too. Also I have to make both test_array and x 1d arrays (shape (0,) and (1,) respectively). And the dtype field is S10, large enough to contain 'TEXT'.

    In [56]: test_array = np.zeros((0,), dtype='S10, i4, i4')
    
    In [57]: x = np.array([("TEST",1,1)], dtype='S10, i4, i4')
    
    In [58]: test_array = np.concatenate((test_array, x))
    
    In [59]: test_array = np.concatenate((test_array, x))
    
    In [60]: test_array
    Out[60]: 
    array([('TEST', 1, 1), ('TEST', 1, 1)], 
          dtype=[('f0', 'S'), ('f1', '

    Here's an example of building the array from a list of tuples:

    In [75]: xl=('test',1,1)
    
    In [76]: np.array([xl]*3,dtype='S10,i4,i4')
    Out[76]: 
    array([('test', 1, 1), ('test', 1, 1), ('test', 1, 1)], 
          dtype=[('f0', 'S10'), ('f1', '

提交回复
热议问题