如何在Python Numpy Arrarys中使用自定义数据类型

362 阅读2分钟

作为python的一个扩展包,NumPy提供了比python更丰富的数据类型。你可以在NumPy的官方网站上看到所有的NumPy数据类型。数据类型对象(也被称为type对象)主要用于描述数组元素的数据类型、大小和字节顺序。它也可以用来创建结构化数据。例如,Int64和float32是dtype对象的常见实例。

1.如何创建NumPy dtype对象

  1. 创建NumPydtype对象的语法格式。

    import numpy as np
    
    np.dtype(object)
    
  2. 创建NumPydtype对象的例子。

    >>> import numpy as np # import numpy package.
    >>>
    >>> custom_dtype = np.dtype(np.float16) # call the numpy package's dtype() function to create a custom data type, the custom data type extends the np.float16 data type.
    >>>
    >>> print(custom_dtype) # print out the custom data type.
    float16
    
  3. NumPy中的每个数据类型都有一个独特的字符代码,这被称为数据类型识别代码。

2.如何使用自定义NumPy dtype对象的例子

  1. 下面的例子将使用数据类型识别码来创建一个NumPy数据类型对象,然后将该数据类型对象应用于NumPy的ndarray。

    >>> import numpy as np # import the python numpy library
    >>>
    >>> dt_score = np.dtype([('score','f2')]) # define a custom numpy data type to save scores, the first element is the score number, the second element is the score number format.
    >>>
    >>> print(dt_score) # print out the customezed numpy data type.
    [('score', '<f2')]
    >>>
    >>> ndarr = np.array([(88,),(99,),(100,)], dtype = dt_score) # create an numpy ndarray, and set the array element data type to the above custom data type.
    >>>
    >>> print(ndarr) # print out the ndarray, you can find that the score number for each element has been changed to floating number.
    [( 88.,) ( 99.,) (100.,)]
    >>>
    >>> print(ndarr.dtype) # check the ndarray data type.
    [('score', '<f2')]
    >>>
    >>> print(ndarr['score']) # get the score in the ndarray. 
    [ 88.  99. 100.]
    
  2. 一般来说,结构化数据使用字段来描述一个对象的特征。下面的例子描述了一个软件开发工程师的姓名年龄薪水的特征。

    >>> import numpy as np
    >>>
    >>> engineer = np.dtype([('name','S20'), ('age', 'i1'), ('salary', 'f4')]) # define a structured data type, name is string type, age is integer type, salary is float type.
    >>>
    >>> print(engineer) # print out the custom data type.
    [('name', 'S20'), ('age', 'i1'), ('salary', '<f4')] 
    >>>
    >>> ndarr = np.array([('jerry', 36, 10000.99),('tom', 28, 3000.98)], dtype = engineer)  # apply the custom data type to the numpy array element.
    >>>
    >>> print(ndarr) # print out the numpy ndarray object
    [(b'jerry', 36, 10000.99) (b'tom', 28,  3000.98)]