数据类型

阅读: 8887     评论:0

NumPy支持比Python更多种类的数值类型。下表列出了NumPy中定义的不同数据类型。

数据类型 描述
bool_ 存储为一个字节的布尔值(真或假)
int_ 默认整数,相当于 C 的long,通常为int32或int64
intc 相当于 C 的int,通常为int32或int64
intp 用于索引的整数,相当于 C 的size_t,通常为int32或int64
int8 1个字节(-128 ~ 127)
int16 16 位整数(-32768 ~ 32767)
int32 32 位整数(-2147483648 ~ 2147483647)
int64 64 位整数(-9223372036854775808 ~ 9223372036854775807)
uint8 8 位无符号整数(0 ~ 255)
uint16 16 位无符号整数(0 ~ 65535)
uint32 32 位无符号整数(0 ~ 4294967295)
uint64 64 位无符号整数(0 ~ 18446744073709551615)
float_ float64的简写
float16 半精度浮点:符号位,5 位指数,10 位尾数
float32 单精度浮点:符号位,8 位指数,23 位尾数
float64 双精度浮点:符号位,11 位指数,52 位尾数
complex_ complex128的简写
complex64 复数,由两个 32 位浮点表示(实部和虚部)
complex128 复数,由两个 64 位浮点表示(实部和虚部)
complex256 复数,128位
object Python对象类型
string_ 修正的ASCII字符串类型
unicode_ 修正的Unicode类型

小技巧:int8,int16,int32,int64 可替换为等价的字符串 'i1','i2','i4',其他类型也有类似的缩写。

每个内建类型都有一个唯一的字符代码:

  • 'b':布尔值
  • 'i':符号整数
  • 'u':无符号整数
  • 'f':浮点
  • 'c':复数浮点
  • 'm':时间间隔
  • 'M':日期时间
  • 'O':Python 对象
  • 'S', 'a':字符串
  • 'U':Unicode
  • 'V':原始数据(void)

np.astype:显式地转换数据类型

使用astype时总是生成一个新的数组,即使你传入的dtype与原来的一样。

>>> a = np.arange(1, 6)
>>> a
array([1, 2, 3, 4, 5])
>>> a.dtype
dtype('int32')
>>> float_a = a.astype(np.float64)
>>> float_a.dtype
dtype('float64')

# 字符串转浮点
>>> numeric_string = np.array(['1.23', '-1.20', '33'], dtype=np.string_)
>>> numeric_string
array([b'1.23', b'-1.20', b'33'], dtype='|S5')
>>> numeric_string.astype(float)
array([ 1.23, -1.2 , 33.  ])

# 使用其它数组的dtype
>>> int_array = np.arange(4)
>>> old = np.array([3.4,2.4,11.3])
>>> new = old.astype(int_array.dtype)
>>> old
array([ 3.4,  2.4, 11.3])
>>> new
array([ 3,  2, 11])

Numpy还有一些预先定义的特殊值:

比如:np.nan、np.pi、np.e

np.nan: 缺失值,或者理解为'不是一个数'

import numpy as np 
a = np.array([np.nan,  1,2,np.nan,3,4,5])  
a[~np.isnan(a)]


b = np.array([1,  2+6j,  5,  3.5+5j])  
b[np.iscomplex(b)]

np.pi:圆周率 3.1415926...

np.e:自然数e 2.718281828459045...


 基础知识 创建数组 

评论总数: 0


点击登录后方可评论