NumPy 数组数据类型

NumPy 有一些额外的数据类型,并通过一个字符引用数据类型:i - 整数b - 布尔u - 无符号整数f - 浮点c - 复合浮点数m - timedeltaM - datetimeO - 对象S - 字符串U - unicode 字符串V - 固定的其他类型的内存块(void)

查看数据类型

使用 dtype 属性,查看数组的数据类型

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr) # [1 2 3 4]

print(arr.dtype) # int64 默认打印整数为 8 字节整数

arr = np.array(['apple', 'banana', 'cherry'])

print(arr) # ['apple' 'banana' 'cherry']

print(arr.dtype) #

创建数据类型为字符串的数组

使用 dtype 属性转换成字符串类型

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='S')

print(arr) # [b'1' b'2' b'3' b'4']

print(arr.dtype) # |S1 字符串

创建数据类型为 4 字节整数的数组

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='i4')

print(arr) # [1 2 3 4]

print(arr.dtype) # int32 4 字节整数

如果无法进行数据类型的转换,会报错

无法将非整数字符串(比如’a’)转换成整数

import numpy as np

arr = np.array(['a', '2', '3'], dtype='i')

print(arr) # ValueError: invalid literal for int() with base 10: 'a'

数据类型转换

使用方法 astype 可以将现有的数组转换成为指定数据类型的数组数据类型可以使用字符串指定:f ==> float i ==> int也可以直接用 int float 进行数据类型转换

import numpy as np

arr = np.array([1.1, 2.1, 3.1])

print(arr) # [1.1 2.1 3.1]

print(arr.dtype) # float64

new_arr = arr.astype('i')

print(new_arr) # [1 2 3] 转换成为整型会舍去小数部分

print(new_arr.dtype) # int32

newarr = arr.astype(int)

print(newarr) # [1 2 3] 转换成为整型会舍去小数部分

print(newarr.dtype) # int64

Copyright © 2088 俄罗斯世界杯主题曲_世界杯下一届 - pin8pin8.com All Rights Reserved.
友情链接