1、常量
import numpy as np
print(np.nan == np.nan) # False
print(np.nan != np.nan)
两个numpy.nan是不相等的
ar=np.array([1,2,3,np.nan])
print(ar)
print(np.isnan(ar))
[ 1. 2. 3. nan]
[False False False True]
2、数据类型
常见数据类型
Python 原生的数据类型相对较少, bool、int、float、str等。这在不需要关心数据在计算机中表示的所有方式的应用中是方便的。然而,对于科学计算,通常需要更多的控制。为了加以区分 numpy 在这些类型名称末尾都加了“_”。
下表列举了常用 numpy 基本类型。
类型 备注 说明
bool_ = bool8 8位 布尔类型
int8 = byte 8位 整型
int16 = short 16位 整型
int32 = intc 32位 整型
int_ = int64 = long = int0 = intp 64位 整型
uint8 = ubyte 8位 无符号整型
uint16 = ushort 16位 无符号整型
uint32 = uintc 32位 无符号整型
uint64 = uintp = uint0 = uint 64位 无符号整型
float16 = half 16位 浮点型
float32 = single 32位 浮点型
float_ = float64 = double 64位 浮点型
str = unicode = str0 = unicode Unicode 字符串
datetime64 日期时间类型
timedelta64 表示两个时间之间的间隔
a=np.dtype('b1')
b=np.dtype('i2')
print(a.type,a.itemsize,b.type,b.itemsize)
<class 'numpy.bool_'> 1 <class 'numpy.int16'> 2
数据类型信息
Python 的浮点数通常是64位浮点数,几乎等同于 np.float64。
NumPy和Python整数类型的行为在整数溢出方面存在显着差异,与 NumPy 不同,Python 的int 是灵活的。这意味着Python整数可以扩展以容纳任何整数并且不会溢出。
Machine limits for integer types.
i16 = np.iinfo(np.int16)
print(ii16.min) # -32768
print(ii16.max) # 32767
ii32 = np.iinfo(np.int32)
print(ii32.min) # -2147483648
print(ii32.max)
-32768
32767
-2147483648
2147483647
3、时间日期和时间增量
datetime64 基础
在 numpy 中,我们很方便的将字符串转换成时间日期类型 datetime64(datetime 已被 python 包含的日期时间库所占用)。
datatime64是带单位的日期时间类型,其单位如下:
日期单位 代码含义 时间单位 代码含义
Y 年 h 小时
M 月 m 分钟
W 周 s 秒
D 天 ms 毫秒
-
- us 微秒
-
- ns 纳秒
-
- ps 皮秒
-
- fs 飞秒
-
- as 阿托秒
注意:
- as 阿托秒
1秒 = 1000 毫秒(milliseconds)
1毫秒 = 1000 微秒(microseconds)
a = np.datetime64('2020-03-01')
print(a, a.dtype) # 2020-03-01 datetime64[D]
b= np.datetime64('2020-03')
print(b, b.dtype)
2020-03-01 datetime64[D]
2020-03 datetime64[M]
a = np.arange('2020-08-01', '2020-08-10', dtype=np.datetime64)
print(a)
['2020-08-01' '2020-08-02' '2020-08-03' '2020-08-04' '2020-08-05'
'2020-08-06' '2020-08-07' '2020-08-08' '2020-08-09']
datetime64 和 timedelta64 运算
dt = datetime.datetime(year=2020, month=6, day=1, hour=20, minute=5, second=30)
dt64 = np.datetime64(dt, 's')
print(dt64, dt64.dtype)
2020-06-01T20:05:30 datetime64[s]