常量
1.空值
numpy.nan
注:两个nan是不相等的
2.无穷大
numpy.inf
3.圆周率
numpy.pi
4.自然常数e
numpy.e
数据类型
常见的数据类型
创建数据类型dtype
举例
import numpy as np
type = np.dtype([('name','S10'),('score','f4')])
a = np.array([('alen',88.8),('lee',90.25),('teen',68.56)],dtype=type)
print(a)
时间相关
datatime64
datatime64是带单位的日期时间类型
a = np.datetime64('2020-03-01')
print(a, a.dtype) # 2020-03-01 datetime64[D]
a = np.datetime64('2020-03')
print(a, a.dtype) # 2020-03 datetime64[M]
a = np.datetime64('2020-03-08 20:00:05')
print(a, a.dtype) # 2020-03-08T20:00:05 datetime64[s]
a = np.datetime64('2020-03-08 20:00')
print(a, a.dtype) # 2020-03-08T20:00 datetime64[m]
a = np.datetime64('2020-03-08 20')
print(a, a.dtype) # 2020-03-08T20 datetime64[h]
强制指定使用的单位
注释为输出结果
a = np.datetime64('2020-03', 'D')
print(a, a.dtype) # 2020-03-01 datetime64[D]
a = np.datetime64('2020-03', 'Y')
print(a, a.dtype) # 2020 datetime64[Y]
print(np.datetime64('2020-03') == np.datetime64('2020-03-01')) # True
print(np.datetime64('2020-03') == np.datetime64('2020-03-02')) #False
使用arange()创建 datetime64 数组,用于生成日期范围
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']
print(a.dtype) # datetime64[D]
a = np.arange('2020-08-01 20:00', '2020-08-10', dtype=np.datetime64)
print(a)
# ['2020-08-01T20:00' '2020-08-01T20:01' '2020-08-01T20:02' ...
# '2020-08-09T23:57' '2020-08-09T23:58' '2020-08-09T23:59']
print(a.dtype) # datetime64[m]
a = np.arange('2020-05', '2020-12', dtype=np.datetime64)
print(a)
# ['2020-05' '2020-06' '2020-07' '2020-08' '2020-09' '2020-10' '2020-11']
print(a.dtype) # datetime64[M]
datetime64 和 timedelta64 运算
timedelta64也是带单位的,和datatime64计算时自动与datatime64中较小的单位保持一致
a = np.datetime64('2020-03-08') - np.datetime64('2020-03-07')
b = np.datetime64('2020-03-08') - np.datetime64('202-03-07 08:00')
c = np.datetime64('2020-03-08') - np.datetime64('2020-03-07 23:00', 'D')
print(a, a.dtype) # 1 days timedelta64[D]
print(b, b.dtype) # 956178240 minutes timedelta64[m]
print(c, c.dtype) # 1 days timedelta64[D]
a = np.datetime64('2020-03') + np.timedelta64(20, 'D')
b = np.datetime64('2020-06-15 00:00') + np.timedelta64(12, 'h')
print(a, a.dtype) # 2020-03-21 datetime64[D]
print(b, b.dtype) # 2020-06-15T12:00 datetime64[m]
numpy.datetime64 与 datetime.datetime 相互转换
import numpy as np
import datetime
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]
dt2 = dt64.astype(datetime.datetime)
print(dt2, type(dt2))
# 2020-06-01 20:05:30 <class 'datetime.datetime'>
busday工作日功能
weekmask参数可以指定一周中哪些是工作日
a = np.is_busday('2020-07-10', weekmask=[1, 1, 1, 1, 1, 0, 0])
b = np.is_busday('2020-07-10', weekmask=[1, 1, 1, 1, 0, 0, 1])
print(a) # True
print(b) # False
将指定的偏移量应用于工作日,单位天(‘D’)。计算下一个工作日,如果当前日期为非工作日,默认报错。可以指定 forward 或 backward 规则来避免报错。(一个是向前取第一个有效的工作日,一个是向后取第一个有效的工作日)
import numpy as np
# 2020-07-10 星期五
a = np.busday_offset('2020-07-10', offsets=1)
print(a) # 2020-07-13
a = np.busday_offset('2020-07-11', offsets=1)
print(a)
# ValueError: Non-business day date in busday_offset
a = np.busday_offset('2020-07-11', offsets=0, roll='forward')
b = np.busday_offset('2020-07-11', offsets=0, roll='backward')
print(a) # 2020-07-13
print(b) # 2020-07-10
a = np.busday_offset('2020-07-11', offsets=1, roll='forward')
b = np.busday_offset('2020-07-11', offsets=1, roll='backward')
print(a) # 2020-07-14
print(b) # 2020-07-13
统计一个 datetime64[D] 数组中的工作日天数。
import numpy as np
# 2020-07-10 星期五
begindates = np.datetime64('2020-07-10')
enddates = np.datetime64('2020-07-20')
a = np.arange(begindates, enddates, dtype='datetime64')
b = np.count_nonzero(np.is_busday(a))
print(a)
# ['2020-07-10' '2020-07-11' '2020-07-12' '2020-07-13' '2020-07-14'
# '2020-07-15' '2020-07-16' '2020-07-17' '2020-07-18' '2020-07-19']
print(b) # 6
数组的创建ndarray
1.用现有数据创建ndarray
(1)array()函数创建
a = np.array([0, 1, 2, 3, 4])
(2)asarray()函数创建
x = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
y = np.array(x)
z = np.asarray(x)
【注】两者的区别是:当数据源是ndarray 时,array()仍然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray()不会
(3)通过fromfunction()函数进行创建
该函数可从函数中创建数组
函数定义:def fromfunction(function, shape, **kwargs):
function为函数,shape为数组形状,还可以添加dtype参数
import numpy as np
def f(x, y):
return 10 * x + y
x = np.fromfunction(f, (5, 4), dtype=int)
print(x)
# [[ 0 1 2 3]
# [10 11 12 13]
# [20 21 22 23]
# [30 31 32 33]
# [40 41 42 43]]
x = np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
print(x)
# [[ True False False]
# [False True False]
# [False False True]]
x = np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
print(x)
# [[0 1 2]
# [1 2 3]
# [2 3 4]]
创建0/1数组
机器学习中常做的第一件事就是初始化参数,要用常数(通常0)来创建固定大小的矩阵
(1)0数组
np.zeros()
例如:
x = np.zeros(5)
print(x) # [0. 0. 0. 0. 0.]
x = np.zeros([2, 3])
print(x)
# [[0. 0. 0.]
# [0. 0. 0.]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.zeros_like(x)
print(y)
# [[0 0 0]
# [0 0 0]]
(2)1数组
np.ones()
x = np.ones(5)
print(x) # [1. 1. 1. 1. 1.]
x = np.ones([2, 3])
print(x)
# [[1. 1. 1.]
# [1. 1. 1.]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.ones_like(x)
print(y)
# [[1 1 1]
# [1 1 1]]
(3)空数组
np.empty()
x = np.empty(5)
print(x)
# [1.95821574e-306 1.60219035e-306 1.37961506e-306
# 9.34609790e-307 1.24610383e-306]
x = np.empty((3, 2))
print(x)
# [[1.60220393e-306 9.34587382e-307]
# [8.45599367e-307 7.56598449e-307]
# [1.33509389e-306 3.59412896e-317]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.empty_like(x)
print(y)
# [[ 7209029 6422625 6619244]
# [ 100 707539280 504]]
(4)创建单位矩阵
np.eye()函数,创建指定维数的单位数组
np.identity()函数,创建指定维数的单位矩阵
x = np.eye(4)
print(x)
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]]
x = np.eye(2, 3)
print(x)
# [[1. 0. 0.]
# [0. 1. 0.]]
x = np.identity(4)
print(x)
# [[1. 0. 0. 0.]
# [0. 1. 0. 0.]
# [0. 0. 1. 0.]
# [0. 0. 0. 1.]]
(5)对角线数组
np.diag()函数,提取对角线或构造对角数组
x = np.arange(9).reshape((3, 3))
print(x)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]
print(np.diag(x)) # [0 4 8]
print(np.diag(x, k=1)) # [1 5]
print(np.diag(x, k=-1)) # [3 7]
v = [1, 3, 5, 7]
x = np.diag(v)
print(x)
# [[1 0 0 0]
# [0 3 0 0]
# [0 0 5 0]
# [0 0 0 7]]
(6)常数数组
np.full()函数
x = np.full((2,), 7)
print(x)
# [7 7]
x = np.full(2, 7)
print(x)
# [7 7]
x = np.full((2, 7), 7)
print(x)
# [[7 7 7 7 7 7 7]
# [7 7 7 7 7 7 7]]
x = np.array([[1, 2, 3], [4, 5, 6]])
y = np.full_like(x, 7)
print(y)
# [[7 7 7]
# [7 7 7]]
3.利用某个数值范围创建ndarray
-
arange()函数:返回给定间隔内的均匀间隔的值。
-
linspace()函数:返回指定间隔内的等间隔数字。
-
logspace()函数:返回数以对数刻度均匀分布。
-
numpy.random.rand() 返回一个由[0,1)内的随机数组成的数组。
-
np.around()函数返回一个四舍五入后的值,可指定小数点精度
x = np.arange(5)
print(x) # [0 1 2 3 4]
x = np.arange(3, 7, 2)
print(x) # [3 5]
x = np.linspace(start=0, stop=2, num=9)
print(x)
# [0. 0.25 0.5 0.75 1. 1.25 1.5 1.75 2. ]
x = np.logspace(0, 1, 5)
print(np.around(x, 2))
# [ 1. 1.78 3.16 5.62 10. ]
x = np.random.random(5)
print(x)
# [0.41768753 0.16315577 0.80167915 0.99690199 0.11812291]
x = np.random.random([2, 3])
print(x)
# [[0.41151858 0.93785153 0.57031309]
# [0.13482333 0.20583516 0.45429181]]
4.结构数组的创建
先定义结构,再用np.array()创建数组,dtype为定义的结构
(1)用字典定义结构
import numpy as np
personType = np.dtype({
'names': ['name', 'age', 'weight'],
'formats': ['U30', 'i8', 'f8']})
a = np.array([('Liming', 24, 63.9), ('Mike', 15, 67.), ('Jan', 34, 45.8)],
dtype=personType)
print(a, type(a))
# [('Liming', 24, 63.9) ('Mike', 15, 67. ) ('Jan', 34, 45.8)]
# <class 'numpy.ndarray'>
(2)用包含多个元组的列表定义结构
import numpy as np
personType = np.dtype([('name', 'U30'), ('age', 'i8'), ('weight', 'f8')])
a = np.array([('Liming', 24, 63.9), ('Mike', 15, 67.), ('Jan', 34, 45.8)],
dtype=personType)
print(a, type(a))
# [('Liming', 24, 63.9) ('Mike', 15, 67. ) ('Jan', 34, 45.8)]
# <class 'numpy.ndarray'>
# 结构数组的取值方式和一般数组差不多,可以通过下标取得元素:
print(a[0])
# ('Liming', 24, 63.9)
print(a[-2:])
# [('Mike', 15, 67. ) ('Jan', 34, 45.8)]
# 我们可以使用字段名作为下标获取对应的值
print(a['name'])
# ['Liming' 'Mike' 'Jan']
print(a['age'])
# [24 15 34]
print(a['weight'])
# [63.9 67. 45.8]
数组的属性
- numpy.ndarray.ndim用于返回数组的维数(轴的个数)也称为秩,一维数组的秩为 1,二维数组的秩为 2,以此类推。
- numpy.ndarray.shape表示数组的维度,返回一个元组,这个元组的长度就是维度的数目,即 ndim 属性(秩)。
- numpy.ndarray.size数组中所有元素的总量,相当于数组的shape中所有元素的乘积,例如矩阵的元素总量为行与列的乘积。
- numpy.ndarray.dtype ndarray 对象的元素类型。
- numpy.ndarray.itemsize以字节的形式返回数组中每一个元素的大小。