numpy(二)——数据类型

numpy(二)——数据类型

import numpy as np

“数据类型,即dtype,是一个特殊的对象,它包含了ndarray需要为某一个类型数据所申明的内存块信息”——《利用Python进行数据分析 第二版》P92

一个ndarray在被创建时,可以显式地指定其数据类型,而指定的方式不一而同,一般来说,有以下几种:

  • 通过数据类型的字符串指定

arr_float16 = np.array([1,2,3],dtype="float16") #指定数据类型后,不管输入的原列表的数据类型是什么,都会按照指定的类型进行输出
arr_float16
array([ 1.,  2.,  3.], dtype=float16)
arr_int8 = np.array([1,2,3],dtype="int8")
arr_int8
array([1, 2, 3], dtype=int8)
arr_bool = np.array([True,False,True,False],dtype="bool")
arr_bool
array([ True, False,  True, False], dtype=bool)
  • 通过数据类型字符串指定过于繁琐,因此也可以通过类型代码字符串进行指定

arr_f2 = np.array([1,2,3],dtype="f2") #与上述arr_float16完全等价
arr_f2
array([ 1.,  2.,  3.], dtype=float16)
arr_i1 = np.array([1,2,3],dtype="i1")
arr_i1
array([1, 2, 3], dtype=int8)
arr_bool = np.array([True,False,True,False],dtype="?")
arr_bool
array([ True, False,  True, False], dtype=bool)
  • 通过np对象指定

arr_int16 = np.array([1,2,3],dtype=np.int16)
arr_int16
array([1, 2, 3], dtype=int16)
arr_float32 = np.array([1,2,3],dtype=np.float32)
arr_float32
array([ 1.,  2.,  3.], dtype=float32)
  • 通过Python原生数据类型指定

arr_int = np.array([1,2,3],dtype=int)
arr_int
array([1, 2, 3])
arr_float = np.array([1,2,3],dtype=float)
arr_float
array([ 1.,  2.,  3.])

不过,在这种情况下,你无法指定数据类型在内存中的所占字节多少,默认int为32位,float为64位

print(arr_int.dtype)
print(arr_float.dtype)
int32
float64

numpy中所有可用的数据类型见《利用Python进行数据分析 第二版》P93页表4-2,以及《Python数据科学手册》P35表2-1

需要注意的地方:

  • 一般情况下,不必过于思考应该采用哪种字节长度的数据类型,“通常你只需要关系数据的大类,比如是否是浮点型、整数、布尔值、字符串或某个Python对象”(《利用Python进行数据分析 第二版》P92)。当只有在操作危及到你的内存容量的大数据集时,你才需要精打细算,仔细考虑究竟应该采用哪种数据类型,以节约内存,提高数据处理的效率。

关于string_和unicode_数据类型

这两个类型都指向字符或字符串数据类型,但是二者仍与区别,以及有一些值得注意的地方:

  • string_类型的类型代码是S,面向的数据类型是ascii字符串,例如生成一个长度10以内的ascii类型字符串,可以用"S10"

arr_str = np.array(["hello","world","how","are","you","today"],dtype = "S10")
arr_str
array([b'hello', b'world', b'how', b'are', b'you', b'today'],
      dtype='|S10')

可以看到,如果指定的长度小于输入中的某些字符串长度,则输出会按照指定长度进行截取。
并且也可以发现,由于string_是代表ascii类型字符串,因此,得到的输出结果是bytes类型的字符对象,也就是用十进制ascii值表示的二进制字符数据。需要decode解码之后才可以变为str类型的字符串。

arr_str_3 = np.array(["hello","world","how","are","you","today"],dtype = "S3")
arr_str_3
array([b'hel', b'wor', b'how', b'are', b'you', b'tod'],
      dtype='|S3')
arr_str[1][0] #"w"的ascii值是119
119
arr_str[1].decode()
'world'

并且,当我们输入非ascii字符的时候,就会因此错误

arr_str_test = np.array(["hello","你好"],dtype="S10")
arr_str_test
---------------------------------------------------------------------------

UnicodeEncodeError                        Traceback (most recent call last)

<ipython-input-58-f3344d50f40e> in <module>
----> 1 arr_str_test = np.array(["hello","你好"],dtype="S10")
      2 arr_str_test


UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
  • unicode_类型的类型代码是U,面向的数据类型是unicode字符串,例如生成一个长度10以内的unicode类型字符串,可以用"U10"

unicode_类型返回的直接就是str类型字符串。至于该类型其余性状,与string基本一致,不再赘述

arr_unicode = np.array(["hello","你好"],dtype="U10")
arr_unicode
array(['hello', '你好'],
      dtype='<U10')

数据类型转换——astype方法

当一个数组生成后,数据类型也随之被确定,但是仍可用astype方法对其数据类型进行转换,这个方法可以生成一个新的数组

arr1 = np.array([1,2,3]) #如果不指定,那么就是int32
arr1.dtype
dtype('int32')
arr2 = arr1.astype("float64")
arr2.dtype
dtype('float64')

关于astype的注意点:如果想把一个浮点类型数组转成整形,则会丢失小数点后的部分,如9.9转型后将会成为9,-2.7会变成-2。更多细节详见《利用Python进行数据分析 第二版》P93

在最后,仍有一点需要注意:与Python列表不同,numpy数组中的元素数据类型必须相同,如有不同,则自动向上转型:

arr_test = np.array([1,1.5,2,"你好"])
arr_test
array(['1', '1.5', '2', '你好'],
      dtype='<U32')

猜你喜欢

转载自blog.csdn.net/weixin_40321125/article/details/89710505