numpy---(上)

Numpy

Numpy ndarray

N维数组对象ndarray, 是一系列同类型数据的集合, 索引以0下标开始, 创建一个ndarray对象, 需调用array函数:

numpy.array(object, dtype = None, copy = True, order = None, subok = False, ndmin = 0)
名称 描述
object 数组或嵌套的数列
dtype 数组元素的数据类型, 可选, 默认为None
copy 是否需要复制, 可选, 默认为True
order 创建数组的样式, C为行方向, F为列方向, A为任意方向(默认), 默认为None
subok 默认返回一个与基类类型一致的数组, 默认为False
ndmin 指定生成数组的最小维度, 默认为0

实例

import numpy as np
a = np.array([1, 2, 3])
print(a)    # [1 2 3]

# 多一个维度
a1 = np.array([[1, 2],[3, 4]])
print(a1)   
# [[1 2]
#   [3 4]]

# 最小维度
a2 = np.array([1,2, 3, 4, 5], ndmin=2)
print(a2)   # [[1 2 3 4 5]]

# dtype参数
a3 = np.array([1, 2, 3], dtype=complex)
print(a3)   # [1.+0.j 2.+0.j 3.+0.j]

数据类型

  • numpy支持的数据类型比python内置的数据类型多很多, 基本上可以和C语言的数据类型对应上.
  • numpy的数值类型实际上是dtype对象的实例, 并对应唯一的字符, np.int32, np.float32等.

数据类型对象(dtype)

  • 数据类型对象是用来描述与数组对象的内存区如何使用, 依赖于数组的类型, 数据的大小, 数据的字节顺序, 结构化类型下字段的名称等等.
  • 字节顺序是通过对数据预先设定'<'或'>'来决定的, '<'意味着小端法, 即最小值存储在最小的地址, 即低位在最前面; '>'意味着大端法, 即高位放在前面.
num.dtype(object, align, copy)

# object 要转换为的数据类型对象
# align  若为true时, 填充字段使其为类似C的结构体
# copy	 复制dtype对象, 若为false, 则是对内置函数类型对象的引用
  • 每个内建类型都对应一个唯一定义的字符代码
字符 对应类型
b 布尔型
i 有符号整型
u 无符号整型
f 浮点型
c 复数浮点型
m timedelta 时间间隔
M datetime 日期时间
O python对象
S,a byte字符串
U Unicode
V 原始数据 void

实例


# 使用标量类型
dt = np.dtype(np.int32)
print(dt)
# int32

# int8, int16, int32, int64四种数据类型可以使用字符串'i1', 'i2', 'i3', 'i4'代替
dt1 = np.dtype('i4')
print(dt1)
# int32

# 字节顺序标注
dt2 = np.dtype('<i4')
print(dt2)
# int32


# 结构化数据类型的使用, 类型字段和对应的实际类型被创建
dt3 = np.dtype([('age', np.int8)])
print(dt3)
# [('age', 'i1')]


# 将数据类型应用于ndarray对象
dt4 = np.dtype([('age', np.int8)])
a4 = np.array([(10,), (20,),(30,)], dtype=dt4)
print(a4)
# [(10,) (20,) (30,)]

print(a4.dtype)
# [('age', 'i1')]


# 类型字段名可以用于存取实际的age列
dt5 = np.dtype([('age', np.int8)])
a5 = np.array([(10,), (20,),(30,)], dtype=dt4)
print(a5['age'])
# [10 20 30]


# 定义一个结构化数据类型student, 包含字符串字段name, 整数字段age, 及浮点子弹marks, 并将这个dtype应用到ndarray对象
student = np.dtype([('name', 'S20'), ('age', 'i1'), ('marks', 'f4')])
a6 = np.array([('abc', 21, 50), ('xyz', 18, 75)], dtype=student)
print(student)
print(a6)

# [('name', 'S20'), ('age', 'i1'), ('marks', '<f4')]
# [(b'abc', 21, 50.) (b'xyz', 18, 75.)]

数组属性

  • 数组的维数为秩, 一维数组的秩为1, 二维数组的秩为2.
  • 每一个线性的数组称为是一个轴(axis), 也就是维度(dimensions), 而轴的数量---秩, 就是数组的维数.
  • axis=0, 表示沿着第0轴进行操作, 即对每个列进行操作;axis=1, 表示沿着第1轴进行操作, 即对每个行进行操作.
属性 说明
ndarray.ndim 秩, 轴的数量或者维度的数量
ndarray.shape 数组的维度, 返回一个元组, 对于矩阵, n行m列,
ndarray.size 数组元素的总个数, n*m
ndarray.dtype 元素类型
ndarray.itemsize 每个元素的大小, 以字节为单位
ndarray.flags 内存信息
ndarray.real 实部
ndarray.imag 虚部
ndarray.data 数组元素的缓冲区(一般通过数组的索引获取元素, 通常这个属性不常用)

创建数组

numpy.empty

  • 用来创建一个指定形状(shape)、数据类型(dtype)且未初始化的数组
numpy.empty(shape, dtype = float, order = 'C')

# shape 数组形状
# dtype 数据类型, 可选
# order 有'C'和'F'两个选项, 分别表示行优先, 和列优先, 在内存中存储元素的顺序
x1 = np.empty([3, 2], dtype=int)
# 数组元素为随机值, 因为未初始化
print(x1)
'''
[[       848          0]
 [       848          0]
 [-997652816        182]]
 '''

numpy.zeros

  • 创建指定大小的数组, 数组元素以0来填充
numpy.zeros(shape, dtype = float, order = 'C')
# 默认为浮点数
x2 = np.zeros(5)
print(x2)
# [0. 0. 0. 0. 0.]


# 设置为整数
x3 = np.zeros((5,), dtype=np.int)
print(x3)
# [0 0 0 0 0]

# 自定义类型
x3 = np.zeros((2,2), dtype=[('x','i4'), ('y','i4')])
print(x3)
'''
[[(0, 0) (0, 0)]
[(0, 0) (0, 0)]]
'''

numpy.ones

numpy.ones(shape, dtype = None, order = 'C')
# 默认为浮点数
x4 = np.ones(5)
print(x4)
# [1. 1. 1. 1. 1.]


# 设置为整型
x4 = np.ones([2, 2], dtype=np.int)
print(x4)
'''
[[1 1]
 [1 1]]
'''

从已有的数组创建数组

numpy.asarray

numpy.asarray(a, dtype = None, order = None)

# a 任意形式的输入参数, 列表, 列表的元组, 元组, 元组的元组, 元组的列表, 多维数组
# dtype  数据类型, 可选
# order  可选, 有C和F两个选项, 行优先和列优先

# 将列表转换为ndarray
lst1 = [1, 2, 3]
x6 = np.asarray(lst1)
print(x6)
# [1 2 3]


# 将元组转换为ndarray
t1 = (1, 2, 3)
x7 = np.asarray(t1)
print(x7)


# 将元组转换为ndarray
t1 = (1, 2, 3)
x7 = np.asarray(t1)
print(x7)
# [1 2 3]


# 将元组的列表转换为ndarray
lst2 = [(1, 2, 3), (4, 5)]
x8 = np.asarray(lst2)
print(x8)
# [(1, 2, 3) (4, 5)]


# 设置dtype参数
x9 = np.asarray(lst1, dtype=float)
print(x9)
# [1. 2. 3.]

numpy.frombuffer

  • 用于实现动态数组, 接受buffer输入参数, 以流的形式读入转化成ndarray对象.
numpy.frombuffer(buffer, dtype = float, count = -1, offset = 0)

# 注意: buffer是字符串时, 要转成bytes, 即在原字符串前加上b.
参数 描述
buffer 任意对象, 会以流的形式读入
dtype 返回数组的数据类型, 可选
count 读取的数据数量, 默认为-1, 读取所有的数据
offset 读取的起始位置, 默认为0
s = b'hello world'
a10 = np.frombuffer(s, dtype='S1')
print(a10)

'''
[b'h' b'e' b'l' b'l' b'o' b' ' b'w' b'o' b'r' b'l' b'd']
'''

numpy.fromiter

  • 从可迭代对象中建立ndarray对象, 返回一维数组.
numpy.fromiter(iterable, dtype, count=-1)
list2 = range(5)
# it = iter(list2)
a11 = np.fromiter(list2, dtype=float)
print(a11)

# [0. 1. 2. 3. 4.]

从数值范围创建数组

numpy.arange

  • 创建数值范围并返回ndarray对象
numpy.arange(start, stop, step, dtype)

# 起始值, 默认为0
# 终止值, 不包含
# 步长, 默认为1
# 返回ndarray的数据类型, 如果没有提供, 则使用输入数据的类型
x11 = np.arange(6)
print(x11)
# [0 1 2 3 4 5]


# 设置返回类型为float
x12 = np.arange(6, dtype=float)
print(x12)
# [0. 1. 2. 3. 4. 5.]


# 设置起始值, 终止值及步长
x13 = np.arange(10, 20, 2)
print(x13)
# [10 12 14 16 18]

numpy.linspace

  • 用于创建一个一维数组, 数组是一个等差数列构成的
np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None)
参数 描述
start 序列的起始值
stop 序列的终止值
num 要生成的等差数列的样本的数量, 默认为50
endpoint 为True时, 数列中包含stop值, 反之不包含, 默认为True
retstep 为True时, 生成的数组会显示间距, 反之不显示
dtype ndarray的数据类型
b1 = np.linspace(1, 10, 10)
print(b1)
# [ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10.]


# 设置元素全部是1的等差数列
b2 = np.linspace(1, 1, 10)
print(b2)
# [1. 1. 1. 1. 1. 1. 1. 1. 1. 1.]


# 设置endpoint为False, 不包含终止值
b3 = np.linspace(10, 20, 5, endpoint=False)
print(b3)
# [10. 12. 14. 16. 18.]


# 设置间距
b4 = np.linspace(1, 10, 10, retstep=True)
print(b4)
# (array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.]), 1.0)


# 扩展
b5 = np.linspace(1, 10, 10).reshape(10, 1)
print(b5)
'''
[[ 1.]
 [ 2.]
 [ 3.]
 [ 4.]
 [ 5.]
 [ 6.]
 [ 7.]
 [ 8.]
 [ 9.]
 [10.]]
'''

numpy.logspace

  • 用于创建一个等比数列
np.logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None)
参数 描述
start 序列的起始值: base ** start
stop 序列的终止值: base ** stop
num 要生成的等步长的样本的数量值, 默认为50
endpoint 为true时, 数列中包含stop值, 反之不包含
base 对数log的底数
dtype ndarray的数据类型

# 默认底数是10
b6 = np.logspace(1.0, 2.0, num=10)
print(b6)
'''
[ 10.          12.91549665  16.68100537  21.5443469   27.82559402
  35.93813664  46.41588834  59.94842503  77.42636827 100.        ]
'''


# 将底数设置为2
b7 = np.logspace(0, 9, 10, base=2)
print(b7)
'''
[  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]
'''

切片和索引

  • 通过索引和切片访问和修改ndarray对象的内容, 索引下标从0开始, 切片对象通过内置函数slice设置start, stop及step参数, 从而切割出一个新数组,

  • 也可以通过冒号分隔切片参数 start: stop: step来进行切片操作

b8 = np.arange(10)
s1 = slice(2, 7, 2)
print(b8[s1])
# [2 4 6]

print(b8[2:7:2])
# [2 4 6]

print(b8[5])
# 5

print(b8[2:])
# [2 3 4 5 6 7 8 9]

print(b8[2:5])
# [2 3 4]
  • 多维数组同样适用上述索引提取方法
a20 = np.array([[1, 2, 3], [3, 4, 5], [4, 5, 6]])
print(a20)
print('从数组索引 a20[1:] 处开始切割')
print(a20[1:])

'''
[[1 2 3]
 [3 4 5]
 [4 5 6]]
从数组索引 a20[1:] 处开始切割
[[3 4 5]
 [4 5 6]]
'''
  • 切片还可以包括省略号..., 来使选择元组的长度与数组的维度相同.
print(a20[..., 1])
[2 4 5]

print(a20[1, ...])
print('*' * 20)
print(a20[..., 1:])
'''
[3 4 5]
********************
[[2 3]
 [4 5]
 [5 6]]
'''

高级索引

整数数组索引

# 获取数据中(0, 0), (1, 1)和(2, 0)位置处的元素
x20 = np.array([[1, 2], [3, 4], [5, 6]])
y20 = x20[[0, 1, 2], [0, 1, 0]]
print(y20)
# [1 4 5]


x21 = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]])
print('数组为:\n{}\n'.format(x21))

rows = np.array([[0, 0], [3, 3]])
cols = np.array([[0, 2], [0, 2]])
y21 = x21[rows, cols]
print('这个数组的四个角元素:\n{}'.format(y21))


'''
数组为:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

这个数组的四个角元素:
[[ 0  2]
 [ 9 11]]
'''


a0 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b0 = a0[1:3, 1:3]
c0 = a0[1:3, [1, 2]]
d0 = a0[..., 1:]
print(a0)
print('*' * 30)
print(b0)
print('*' * 30)
print(c0)
print('*' * 30)
print(d0)

'''
[[1 2 3]
 [4 5 6]
 [7 8 9]]
******************************
[[5 6]
 [8 9]]
******************************
[[5 6]
 [8 9]]
******************************
[[2 3]
 [5 6]
 [8 9]]
'''

布尔索引

  • 通过一个布尔数组来索引目标数组.
# 获取大于5的元素
print(x21[x21 > 5])
# [ 6  7  8  9 10 11]


# 使用 ~ 取补运算符来过滤NaN
a20 = np.array([np.nan, 1, 2, np.nan, 3, 4, 5])
print(a20)
print(a20[~np.isnan(a20)])
'''
[nan  1.  2. nan  3.  4.  5.]
[1. 2. 3. 4. 5.]
'''


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

花式索引

  • 利用整数数组进行索引, 根据索引数组的值作为目标数组某个轴的下标来取值.
  • 如果使用一维整型数组作为索引, 且目标数组也是一维数组, 索引的结果就是对应位置的元素; 如果目标数组是二维数组, 那就是对应下标的行.
  • 花式索引是将数据复制到新数组中.
# 传入顺序索引数组
import numpy as np
x31 = np.arange(32).reshape(8, 4)
print(x31)
print('-' * 20)
print(x31[[4, 2, 1, 7]])
'''
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]
 [24 25 26 27]
 [28 29 30 31]]
--------------------
[[16 17 18 19]
 [ 8  9 10 11]
 [ 4  5  6  7]
 [28 29 30 31]]
'''

# 传入倒序索引数组
print(x31[[-4, -2, -1, -7]])
'''
[[16 17 18 19]
 [24 25 26 27]
 [28 29 30 31]
 [ 4  5  6  7]]
'''


# 传入多个索引数组, 使用np.ix_
print(x31[np.ix_([1, 5, 7, 2],[0, 3, 1, 2])])
'''
[[ 4  7  5  6]
 [20 23 21 22]
 [28 31 29 30]
 [ 8 11  9 10]]
'''
posted @ 2019-01-17 16:06  凯旋.Lau  阅读(180)  评论(0编辑  收藏  举报