Define dtypes in NumPy using a list?

后端 未结 1 733
谎友^
谎友^ 2021-01-06 15:43

I just am having a problem with NumPy dtypes. Essentially I\'m trying to create a table that looks like the following (and then save it using rec2csv):

              


        
相关标签:
1条回答
  • 2021-01-06 16:16

    The following code might help:

    import numpy as np
    
    dt = np.dtype([('name1', '|S10'), ('name2', '<f8')])
    tuplelist=[
        ('n1', 1.2),
        ('n2', 3.4),    
         ]
    arr = np.array(tuplelist, dtype=dt)
    
    print(arr['name1'])
    # ['n1' 'n2']
    print(arr['name2'])
    # [ 1.2  3.4]
    

    Your immediate problem was that np.dtype expects the format specifiers to be numpy types, such as '|S10' or '<f8' and not Python types, such as str or float. If you type help(np.dtype) you'll see many examples of how np.dtypes can be specified. (I've only mentioned a few.)

    Note that np.array expects a list of tuples. It's rather particular about that.

    A list of lists raises TypeError: expected a readable buffer object.

    A (tuple of tuples) or a (tuple of lists) raises ValueError: setting an array element with a sequence.

    0 讨论(0)
提交回复
热议问题