目录

NumPy - 数据类型

NumPy支持比Python更多种类的数值类型。 下表显示了NumPy中定义的不同标量数据类型。

Sr.No. 数据类型和描述
1

bool_

存储为字节的布尔值(True或False)

2

int_

默认整数类型(与C long相同;通常为int64或int32)

3

intc

与C int相同(通常为int32或int64)

4

intp

用于索引的整数(与C ssize_t相同;通常为int32或int64)

5

int8

字节(-128到127)

6

int16

整数(-32768至32767)

7

int32

整数(-2147483648至2147483647)

8

int64

整数(-9223372036854775808至9223372036854775807)

9

uint8

无符号整数(0到255)

10

uint16

无符号整数(0到65535)

11

uint32

无符号整数(0到4294967295)

12

uint64

无符号整数(0到18446744073709551615)

13

float_

float64的简写

14

float16

半精度浮点数:符号位,5位指数,10位尾数

15

float32

单精度浮点数:符号位,8位指数,23位尾数

16

float64

双精度浮点数:符号位,11位指数,52位尾数

17

complex_

complex128的简写

18

complex64

复数,由两个32位浮点数(实部和虚部)表示

19

complex128

复数,由两个64位浮点数(实数和虚数组件)表示

NumPy数字类型是dtype(数据类型)对象的实例,每个对象都具有唯一的特征。 dtypes可用作np.bool_,np.float32等。

Data Type Objects (dtype)

数据类型对象描述对应于数组的固定内存块的解释,具体取决于以下方面 -

  • 数据类型(整数,浮点或Python对象)

  • 数据大小

  • 字节顺序(little-endian或big-endian)

  • 在结构化类型的情况下,每个字段的字段名称,每个字段的数据类型和每个字段占用的内存块的一部分。

  • 如果数据类型是子数组,则其形状和数据类型

字节顺序由前缀“”决定数据类型。 ' '>'表示编码是big-endian(最重要的字节存储在最小的地址中)。

使用以下语法构造dtype对象 -

numpy.dtype(object, align, copy)

参数是 -

  • Object - 要转换为数据类型对象

  • Align - 如果为true,则向字段添加填充以使其类似于C-struct

  • Copy - 制作dtype对象的新副本。 如果为false,则结果引用内置数据类型对象

例子1 (Example 1)

# using array-scalar type 
import numpy as np 
dt = np.dtype(np.int32) 
print dt

输出如下 -

int32

例子2 (Example 2)

#int8, int16, int32, int64 can be replaced by equivalent string 'i1', 'i2','i4', etc. 
import numpy as np 
dt = np.dtype('i4')
print dt 

输出如下 -

int32

例子3 (Example 3)

# using endian notation 
import numpy as np 
dt = np.dtype('>i4') 
print dt

输出如下 -

>i4

以下示例显示了结构化数据类型的使用。 这里,将声明字段名称和相应的标量数据类型。

例子4 (Example 4)

# first create structured data type 
import numpy as np 
dt = np.dtype([('age',np.int8)]) 
print dt 

输出如下 -

[('age', 'i1')] 

例子5 (Example 5)

# now apply it to ndarray object 
import numpy as np 
dt = np.dtype([('age',np.int8)]) 
a = np.array([(10,),(20,),(30,)], dtype = dt) 
print a

输出如下 -

[(10,) (20,) (30,)]

例6

# file name can be used to access content of age column 
import numpy as np 
dt = np.dtype([('age',np.int8)]) 
a = np.array([(10,),(20,),(30,)], dtype = dt) 
print a['age']

输出如下 -

[10 20 30]

例7

以下示例定义了一个名为student的结构化数据类型,其中包含字符串字段“name”, integer field “age”和float field “marks”。 此dtype应用于ndarray对象。

import numpy as np 
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) 
print student

输出如下 -

[('name', 'S20'), ('age', 'i1'), ('marks', '<f4')])

例8

import numpy as np 
student = np.dtype([('name','S20'), ('age', 'i1'), ('marks', 'f4')]) 
a = np.array([('abc', 21, 50),('xyz', 18, 75)], dtype = student) 
print a

输出如下 -

[('abc', 21, 50.0), ('xyz', 18, 75.0)]

每个内置数据类型都有一个唯一标识它的字符代码。

  • 'b' - 布尔值

  • 'i' - (签名)整数

  • 'u' - 无符号整数

  • 'f' - 浮点数

  • 'c' - 复杂浮点

  • 'm' - timedelta

  • 'M' - 日期时间

  • 'O' - (Python)对象

  • 'S', 'a' - (byte-)字符串

  • 'U' - Unicode

  • 'V' - 原始数据(无效)

↑回到顶部↑
WIKI教程 @2018