NumPy Beginner's Guide 2e 带注释源码 二、NumPy 基础入门

# 来源:NumPy Biginner's Guide 2e ch2
>>> from numpy import *

多维数组

# 创建多维数组
>>> m = array([arange(2), arange(2)])
>>> m
array([[0, 1],
       [0, 1]])
# 打印形状
>>> m.shape
(2, 2)

# 创建 2x2 的矩阵
>>> a = array([[1,2],[3,4]])
>>> a
array([[1, 2],
       [3, 4]])
       
# 读取矩阵的每个元素
>>> a[0,0]
1
>>> a[0,1]
2
>>> a[1,0]
3
>>> a[1,1]
4

数值类型

类型描述
bool布尔值,一位
int平台相关整数,int32int64
int8字节(-128 ~ 127
int16整数(-32768 ~ 32767
int32整数(-2 ** 31 ~ 2 ** 31 - 1
int64整数(-2 ** 63 ~ 2 ** 63 - 1
uint8无符号整数(0 ~ 255
uint16无符号整数(0 ~ 65535
uint32无符号整数(0 ~ 2 ** 32 - 1
uint64无符号整数(0 ~ 2 ** 64 - 1
float16半精度浮点,符号位,5 位指数,10 位尾数
float32单精度浮点,符号位,8 位指数,23 位尾数
float64float双精度浮点,符号位,11 位指数,52 位尾数
complex64复数,由两个 32 位浮点表示(实部和虚部)
complex128complex复数,由两个 64 位浮点表示(实部和虚部)
# 每个数据类型都可用作转换函数
>>> float64(42)
42.0
>>> int8(42.0)
42
>>> bool(42)
True
>>> bool(0)
False
>>> bool(42.0)
True
>>> float(True)
1.0
>>> float(False)
0.0

# 复数转整数会抛出错误
>>> int(42.0 + 1.j)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to int

数据类型对象(dtype)

# 从数值类型构造
>>> dtype(float)
dtype('float64')

# 从字符代码构造
>>> dtype('f')
dtype('float32')
>>> dtype('d')
dtype('float64')

# 从双字符代码构造
>>> dtype('f8')
dtype('float64')

# 获取所有字符代码
>>> sctypeDict.keys()
[0, … 'i2', 'int0']
 
# char 属性获取字符代码
>>> t = dtype('Float64')
>>> t.char
'd'

# type 属性获取类型
>>> t.type
<type 'numpy.float64'>

# str 属性获取完整字符串表示
# 第一个字符是字节序,< 表示小端,> 表示大端,| 表示平台的字节序
>>> t.str
'<f8'

# 获取大小
>>> t.itemsize
8

# 许多函数拥有 dtype 参数
# 传入数值类型、字符代码和 dtype 都可以
>>> arange(7, dtype=uint16)
array([0, 1, 2, 3, 4, 5, 6], dtype=uint16)
类型字符代码
bool?, b1
int8b, i1
uint8B, u1
int16h, i2
uint16H, u2
int32i, i4
uint32I, u4
int64q, i8
uint64Q, u8
float16f2, e
float32f4, f
float64f8, d
complex64F4, F
complex128F8, D
strS(可以在S后面添加数字,表示字符串长度,比如S3表示长度为三的字符串,不写则为最大长度)
unicodeU
objectO
voidV

记录类型

# 定义记录类型
# dtype 传入字段列表,字段用名称和类型表示
>>> t = dtype([('name', str_, 40), ('numitems', int32), ('price', float32)])
>>> t
dtype([('name', '|S40'), ('numitems', '<i4'), ('price','<f4')])

# 获取字段
>>> t['name']
dtype('|S40')

# 使用记录类型创建数组
# 否则它会把记录拆开
>>> itemz = array([('Meaning of life DVD', 42, 3.14), ('Butter', 13,2.72)], dtype=t)
>>> itemz[1]
('Butter', 13, 2.7200000286102295)

操作形状

>>> b = array([[[ 0,  1,  2,  3],
                [ 4,  5,  6,  7],
                [ 8,  9, 10, 11]],
               [[12, 13, 14, 15],
                [16, 17, 18, 19],
                [20, 21, 22, 23]]])

# ravel 将数组展开,创建视图
>>> b.ravel()
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,14, 15, 16,
       17, 18, 19, 20, 21, 22, 23])

# flatten 将数组展开,创建副本
>>> b.flatten()
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13,14, 15, 16,
       17, 18, 19, 20, 21, 22, 23])
       
# reshape 用于设置数组形状
# 总数必须一致
>>> b.shape = (6,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])

# 用于转置矩阵
>>> b.transpose()
array([[ 0,  4,  8, 12, 16, 20],
       [ 1,  5,  9, 13, 17, 21],
       [ 2,  6, 10, 14, 18, 22],
       [ 3,  7, 11, 15, 19, 23]])

# resize 用于原地设置形状
# 其它和 reshape 相同
>>> b.resize((2,12))
>>> b
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])

堆叠

>>> a = arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> b = 2 * a
>>> b
array([[ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
       
# 二维数组的轴
# 0:竖直,1:水平
# 三维数组的轴
# 0:纵深,1:竖直,2:水平
       
# 水平堆叠
>>> hstack((a, b))
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])
# 也可以使用 concatenate,指定轴 1(二维数组的水平轴)
>>> concatenate((a, b), axis=1)
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])
       
# 竖直堆叠
>>> vstack((a, b))
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
# 也可以使用 concatenate,指定轴 0(二维数组的数值轴,默认值)
>>> concatenate((a, b), axis=0)
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])

# 纵深堆叠
# 沿第三个轴(深度)堆叠
>>> dstack((a, b))
array([[[ 0,  0],
        [ 1,  2],
        [ 2,  4]],
       [[ 3,  6],
        [ 4,  8],
        [ 5, 10]],
       [[ 6, 12],
        [ 7, 14],
        [ 8, 16]]])

# 按列堆叠
# 对于一维数组,column_stack 使一维数组变成二维数组的列
>>> oned = arange(2)
>>> oned
array([0, 1])
>>> twice_oned = 2 * oned
>>> twice_oned
array([0, 2])
>>> column_stack((oned, twice_oned))
array([[0, 0],
       [1, 2]])
# 对于二维数组,就是 hstack
>>> column_stack((a, b))
array([[ 0,  1,  2,  0,  2,  4],
       [ 3,  4,  5,  6,  8, 10],
       [ 6,  7,  8, 12, 14, 16]])
>>> column_stack((a, b)) == hstack((a, b))
array([[ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True],
       [ True,  True,  True,  True,  True,  True]], dtype=bool)
       
# 按行堆叠
# 对于一维数组,row_stack 使一维数组变成二维数组的行
>>> row_stack((oned, twice_oned))
array([[0, 1],
       [0, 2]])
# 对于二维数组,就是 vstack
>>> row_stack((a, b))
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 0,  2,  4],
       [ 6,  8, 10],
       [12, 14, 16]])
>>> row_stack((a,b)) == vstack((a, b))
array([[ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True],
       [ True,  True,  True]], dtype=bool)

分割

>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
       
# 水平分割,指明分割为多少块
# 不能均分时报错
>>> hsplit(a, 3)
[array([[0],
       [3],
       [6]]),
 array([[1],
       [4],
       [7]]),
 array([[2],
       [5],
       [8]])]
# 也可以使用 split 函数指定轴 1(二维数组的水平轴)
>>> split(a, 3, axis=1)
[array([[0],
       [3],
       [6]]),
 array([[1],
       [4],
       [7]]),
 array([[2],
       [5],
       [8]])]
# 竖直分割,指明分割为多少块
# 不能均分时报错
>>> vsplit(a, 3)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7,8]])]
# 也可以使用 split 函数指定轴 0(二维数组的竖直轴)
>>> split(a, 3, axis=0)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7,8]])]

# 纵深分割
# 我们需要一个三维数组
>>> c = arange(27).reshape(3, 3, 3)
>>> c
array([[[ 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]]])
>>> dsplit(c, 3)
[array([[[ 0],
        [ 3],
        [ 6]],
       [[ 9],
        [12],
        [15]],
       [[18],
        [21],
        [24]]]),
 array([[[ 1],
        [ 4],
        [ 7]],
       [[10],
        [13],
        [16]],
       [[19],
        [22],
        [25]]]),
 array([[[ 2],
        [ 5],
        [ 8]],
       [[11],
        [14],
        [17]],
       [[20],
        [23],
        [26]]])]


属性

# ndim 获取数组维度
>>> b
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]])
>>> b.ndim
2

# size 获取元素数量
>>> b.size
24

# itemsize 获取元素大小
>>> b.itemsize
8

# 这两个乘起来就是数组的大小 nbytes
>>> b.nbytes
192
>>> b.size * b.itemsize
192

# T 属性用于获取转置,和 tranpose 函数一样
>>> b.resize(6,4)
>>> b
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])
>>> b.T
array([[ 0,  4,  8, 12, 16, 20],
       [ 1,  5,  9, 13, 17, 21],
       [ 2,  6, 10, 14, 18, 22],
       [ 3,  7, 11, 15, 19, 23]])
       
# 但如果数组是一维的,我们只能得到它的视图
>>> b.ndim
1
>>> b.T
array([0, 1, 2, 3, 4])

# NumPy 中的复数用 j 表示
>>> b = array([1.j + 1, 2.j + 3])
>>> b
array([ 1.+1.j,  3.+2.j])
>>> b.dtype
dtype('complex128')
>>> b.dtype.str
'<c16'

# real 用于获取实部
>>> b.real
array([ 1.,  3.])

# imag 用于获取虚部
>>> b.imag
array([ 1.,  2.])

# flat 属性获取 numpy.flatiter 对象,它是一个迭代器,用于遍历所有元素
>>> b = arange(4).reshape(2,2)
>>> b
array([[0, 1],
       [2, 3]])
>>> f = b.flat
>>> f
<numpy.flatiter object at 0x103013e00>
>>> for item in f: print item
0
1
2
3

# 也可以直接索引 flatiter 对象
>>> b.flat[2]
2

# 或者多个元素
>>> b.flat[[1,3]]
array([1, 3])

# flat 属性是可设置的,修改 flat 属性的值会修改原始数组
# 设置所有元素
>>> b.flat = 7
>>> b
array([[7, 7],
       [7, 7]])
# 或者仅仅设置某个元素
>>> b.flat[[1,3]] = 1
>>> b
array([[7, 1],
       [7, 1]])

转换

# 转换为 Python 列表
>>> b
array([ 1.+1.j,  3.+2.j])
>>> b.tolist()
[(1+1j), (3+2j)]

# astype 转换数组中的元素类型
# 复数转为整数时会丢掉虚部
>>> b
array([ 1.+1.j,  3.+2.j])
>>> b.astype(int)
/usr/local/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part
  #!/usr/bin/python
array([1, 3])
About This Book, Written as a step-by-step guide, this book aims to give you a strong foundation in NumPy and breaks down its complex library features into simple tasksPerform high performance calculations with clean and efficient NumPy codeAnalyze large datasets with statistical functions and execute complex linear algebra and mathematical computations, Who This Book Is For, This book is for the scientists, engineers, programmers, or analysts looking for a high-quality, open source mathematical library. Knowledge of Python is assumed. Also, some affinity, or at least interest, in mathematics and statistics is required. However, I have provided brief explanations and pointers to learning resources., What You Will Learn, Install NumPy, matplotlib, SciPy, and IPython on various operating systems Use NumPy array objects to perform array operations Familiarize yourself with commonly used NumPy functions Use NumPy matrices for matrix algebra Work with the NumPy modules to perform various algebraic operations Test NumPy code with the numpy.testing module Plot simple plots, subplots, histograms, and more with matplotlib, In Detail, In today's world of science and technology, it's all about speed and flexibility. When it comes to scientific computing, NumPy tops the list. NumPy will give you both speed and high productivity. This book will walk you through NumPy with clear, step-by-step examples and just the right amount of theory. The book focuses on the fundamentals of NumPy, including array objects, functions, and matrices, each of them explained with practical examples. You will then learn about different NumPy modules while performing mathematical operations such as calculating the Fourier transform, finding the inverse of a matrix, and determining eigenvalues, among many others. This book is a one-stop solution to knowing the ins and outs of the vast NumPy library, empowering you to use its wide range of mathematical features to build efficient, high-speed programs.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值