1 创建数组
(1)常量
空值:nan = NaN = NAN
正无穷大:Inf = inf = infty = Infinity = PINF
圆周率:pi = 3.1415926535897932384626433…
e表示自然常数:e = 2.718281828459045235360…
(2)数组类型
常用 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 表示两个时间之间的间隔
创建数组类型
class dtype(object):
def __init__(self, obj, align=False, copy=False):
pass
例:import numpy as np a = np.dtype('b1') print(a.type) # <class 'numpy.bool_'> print(a.itemsize) # 1
数据类型信息
class iinfo(object):
def __init__(self, int_type):
pass
def min(self):
pass
def max(self):
pass
例:import numpy as np ii16 = np.iinfo(np.int16) print(ii16.min) # -32768 print(ii16.max) # 32767
(3)时间日期和时间增量
在 numpy 中,我们很方便的将字符串转换成时间日期类型 datetime64 ( datetime 已被 python 包含的日期时间库所占用)。datatime64 是带单位的日期时间类型
例:import numpy as np a = np.datetime64('2020-03-01') print(a, a.dtype) # 2020-03-01 datetime64[D]
【例】从字符串创建 datetime64 类型时,可以强制指定使用的单位。
import numpy as np a = np.datetime64('2020-03', 'D')
print(a, a.dtype) # 2020-03-01 datetime64[D]
【例】从字符串创建 datetime64 数组时,如果单位不统一,则一律转化成其中最小的单位。
import numpy as np a = np.array(['2020-03', '2020-03-08', '2020-03-08 20:00'], dtype='datetime64')
print(a, a.dtype) # ['2020-03-01T00:00' '2020-03-08T00:00' '2020-03-08T20:00']
datetime64[m]
【例】使用 arange() 创建 datetime64 数组,用于生成日期范围。
import numpy as np 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]
datetime64 和 timedelta64 运算
timedelta64 表示两个 datetime64 之间的差。timedelta64 也是带单位的,并且和相减运算中的两个 datetime64 中的较小的单位保持一致。
生成 timedelta64时,要注意年(‘Y’)和月(‘M’)这两个单位无法和其它单位进行运算(一年有几天?一个月有几个小时?这些都是不确定的)。
import numpy as np a = np.timedelta64(1, 'Y')
print(a) # 1 years
print(np.timedelta64(a, 'D'))
# TypeError: Cannot cast NumPy timedelta64 scalar from metadata [Y] to [D] according to the rule 'same_kind'
【例】timedelta64 的运算。
import numpy as np a = np.timedelta64(1, 'Y')
b = np.timedelta64(6, 'M')
print(a + b) # 18 months
【例】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'>
(4)创建数组
a.``通过array()函数进行创建。
import numpy as np
# 创建一维数组
a = np.array([0, 1, 2, 3, 4])
print(a, type(a)) # [0 1 2 3 4] <class 'numpy.ndarray'>
# 创建二维数组 c = np.array([[11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25], [26, 27, 28, 29, 30], [31, 32, 33, 34, 35]])
print(c, type(c))
# [[11 12 13 14 15] # [16 17 18 19 20] # [21 22 23 24 25] # [26 27 28 29 30] # [31 32 33 34 35]] <class 'numpy.ndarray'>
# 创建三维数组
d = np.array([[(1.5, 2, 3), (4, 5, 6)], [(3, 2, 1), (4, 5, 6)]]) print(d, type(d))
# [[[1.5 2. 3. ] # [4. 5. 6. ]] ## [[3. 2. 1. ] # [4. 5. 6. ]]] <class 'numpy.ndarray'>
b.通过asarray()函数进行创建
array() 和 asarray() 都可以将结构数据转化为 ndarray,但是 array() 和 asarray() 主要区别就是当数据源是ndarray 时,array() 仍然会 copy 出一个副本,占用新的内存,但不改变 dtype 时 asarray() 不会。
import numpy as np
x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
y = np.array(x) z = np.asarray(x)
x[1][2] = 2
print(x,type(x),x.dtype)
# [[1 1 1]
# [1 1 2]
# [1 1 1]] <class 'numpy.ndarray'> int32
print(y,type(y),y.dtype)
# [[1 1 1]
# [1 1 1]
# [1 1 1]] <class 'numpy.ndarray'> int32
print(z,type(z),z.dtype)
# [[1 1 1]
# [1 1 2]
# [1 1 1]] <class 'numpy.ndarray'> int32
【例】更改为较大的dtype时,其大小必须是array的最后一个axis的总大小(以字节为单位)的除数
import numpy as np
x = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
print(x, x.dtype)
# [[1 1 1] # [1 1 1] # [1 1 1]] int32
y=x.dtype ( 'float' )
print(y)
c.通过fromfunction()函数进行创建
给函数绘图的时候可能会用到 fromfunction() ,该函数可从函数中创建数组。
【例】通过在每个坐标上执行一个函数来构造数组。
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]]
依据 ones 和 zeros 填充方式
zeros() 函数:返回给定形状和类型的零数组。
zeros_like() 函数:返回与给定数组形状和类型相同的零数组。
import numpy as np
x = np.zeros(5)
print(x)
# [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]]
1数组
ones() 函数:返回给定形状和类型的1数组。
ones_like() 函数:返回与给定数组形状和类型相同的1数组。
空数组
empty() 函数:返回一个空数组,数组元素为随机数。
empty_like 函数:返回与给定数组具有相同形状和类型的新数组。
单位数组
eye() 函数:返回一个对角线上为1,其它地方为零的单位数组。
identity() 函数:返回一个方的单位数组。
x = np.eye(4)
print(x)
x = np.identity(4)
print(x)
对角数组
import numpy as np
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]
常数数组
full() 函数:返回一个常数数组。
full_like() 函数:返回与给定数组具有相同形状和类型的常数数组。
import numpy as np
x = np.full((2,), 7)
print(x) # [7 7]
利用数值范围来创建ndarray
arange() 函数:返回给定间隔内的均匀间隔的值。
linspace() 函数:返回指定间隔内的等间隔数字。
logspace() 函数:返回数以对数刻度均匀分布。
numpy.random.rand() 返回一个由[0,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'>
利用包含多个元组的列表来定义结构
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)