numpy学习指南3rd2:NumPy基础

代码地址

NumPy 数组对象

arrayattributes.py

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates the dtype and shape attributes
# of ndarray.
#
# Run from the commandline with 
#
#  python3 arrayattributes.py
a = np.arange(5)
print("In: a = arange(5)")

print("In: a.dtype")
print(a.dtype)
#Out: dtype('int64')
print()

print("In: a.shape")
print(a.shape)
#Out: (5,)
print()

print("In: a")
print(a)
#Out[4]: array([0, 1, 2, 3, 4])
print()

m = np.array([np.arange(2), np.arange(2)])

print("In: m")
print(m)
#Out: 
#array([[0, 1],
#       [0, 1]])
print()

print("In: m.shape")
print(m.shape)
#Out: (2, 2)

print("In: m.dtype")
print(m.dtype)
#Out: dtype('int64')
print()

执行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$ python3 arrayattributes.py 
In: a = arange(5)
In: a.dtype
int64

In: a.shape
(5,)

In: a
[0 1 2 3 4]

In: m
[[0 1]
 [0 1]]

In: m.shape
(2, 2)
In: m.dtype
int64
  • 数据类型
类型 描述
bool 用一位存储的布尔类型(值为 TRUE 或 FALSE )
inti 由所在平台决定其精度的整数(一般为 int32 或 int64 )
int8 整数,范围为-128至127
int16 整数,范围为-32 768至32 767
int32 整数,范围为-2^31 至2^31 -1
int64 整数,范围为-2^63 至2^63 -1
uint8 无符号整数,范围为0至255
uint16 无符号整数,范围为0至65 535
uint32 无符号整数,范围为0至2^32 -1
uint64 无符号整数,范围为0至2^64 -1
float16 半精度浮点数(16位):其中用1位表示正负号,5位表示指数,10位表示尾数
float32 单精度浮点数(32位):其中用1位表示正负号,8位表示指数,23位表示尾数
float64 或 float 双精度浮点数(64位):其中用1位表示正负号,11位表示指数,52位表示尾数
complex64 复数,分别用两个32位浮点数表示实部和虚部
complex128 或 complex 复数,分别用两个64位浮点数表示实部和虚部

numericaltypes.py

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates the NumPy numerical types
#  and conversion between them.
#
# Run from the commandline with 
#
#  python3 numericaltypes.py

print("In: float64(42)")
print(np.float64(42))
#Out: 42.0

print("In: int8(42.0)")
print(np.int8(42.0))
#Out: 42

print("In: bool(42)")
print(np.bool(42))
#Out: True
print(np.bool(0))

print("In: bool(42.0)")
print(np.bool(42.0))
#Out: True

print("In: float(True)")
print(np.float(True))
#Out: 1.0
print(np.float(False))

print("In: arange(7, dtype=uint16)")
print(np.arange(7, dtype=np.uint16))
#Out: array([0, 1, 2, 3, 4, 5, 6], dtype=uint16)


print("In: int(42.0 + 1.j)")
try:
   print(np.int(42.0 + 1.j))
except TypeError:
   print("TypeError")
#Type error

print("In: float(42.0 + 1.j)")
print(float(42.0 + 1.j))
#Type error

执行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
$ python3 numericaltypes.py 
In: float64(42)
42.0
In: int8(42.0)
42
In: bool(42)
True
False
In: bool(42.0)
True
In: float(True)
1.0
0.0
In: arange(7, dtype=uint16)
[0 1 2 3 4 5 6]
In: int(42.0 + 1.j)
TypeError
In: float(42.0 + 1.j)
Traceback (most recent call last):
  File "numericaltypes.py", line 47, in <module>
    print(float(42.0 + 1.j))
TypeError: can't convert complex to float
  • 你的赞助是我们前进的动力:

一流企业专家自动化性能接口测试 数据分析 python一对一教,非骗人的培训机构(多数大陆培训机构的老师实际未入门)承接excel合并,电脑自动化操作等工程 并欢迎讨论中医草药风水相学等道家国学

qq群python 测试开发自动化测试 144081101 教你做免费的线上博客(放在简历中增加亮点),自动化测试平台,性能测试工具等,让你有实际项目经验 联系qq:37391319

交流QQ群:python 测试开发自动化测试 144081101 Python数据分析pandas Excel 630011153 中医草药自学自救大数据 391441566 南方中医草药鉴别学习 184175668 中医草药湿热湿疹胃病 291184506 python高级人工智能视觉 6089740

  • 获取元素

elementselection.py

 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
32
33
import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates the selection
# of ndarray elements.
#
# Run from the commandline with 
#
#  python elementselection.py
a = np.array([[1,2],[3,4]])

print("In: a")
print(a)
#Out: 
#array([[1, 2],
#       [3, 4]])

print("In: a[0,0]")
print(a[0,0])
#Out: 1

print("In: a[0,1]")
print(a[0,1])
#Out: 2

print("In: a[1,0]")
print(a[1,0])
#Out: 3

print("In: a[1,1]")
print(a[1,1])
#Out: 4 

执行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ python3 elementselection.py 
In: a
[[1 2]
 [3 4]]
In: a[0,0]
1
In: a[0,1]
2
In: a[1,0]
3
In: a[1,1]
4
  • 字符编码
数据类型 字符编码
整数 i
无符号整数 u
单精度浮点数 f
双精度浮点数 d
布尔值 b
复数 D
字符串 S
unicode字符串 U
void (空) V

charcodes.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates the NumPy dtype character codes.
#
# Run from the commandline with 
#
#  python3 charcodes.py

print("In: arange(7, dtype='f')")
print(np.arange(7, dtype='f'))
#Out: array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.], dtype=float32)

print("In: arange(7, dtype='D')")
print(np.arange(7, dtype='D'))
#Out: array([ 0.+0.j,  1.+0.j,  2.+0.j,  3.+0.j,  4.+0.j,  5.+0.j,  6.+0.j])

执行结果:

1
2
3
4
5
$ python3 charcodes.py
In: arange(7, dtype='f')
[0. 1. 2. 3. 4. 5. 6.]
In: arange(7, dtype='D')
[0.+0.j 1.+0.j 2.+0.j 3.+0.j 4.+0.j 5.+0.j 6.+0.j]
  • 自定义数据类型

dtypeconstructors.py

 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
32
33
34
35
36
37
38
39
40
# -*- coding: utf-8 -*-
# Author:    china-testing#126.com 技术支持qq群:630011153
# CreateDate: 2018-1-8 

import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates the NumPy dtype constructors.
#
# Run from the commandline with 
#
#  python dtypeconstructors.py
# Python中的浮点数类型
print("In: dtype(float)")
print(np.dtype(float))
#Out: dtype('float64')

# 字符编码来指定单精度浮点数类型
print("In: dtype('f')")
print(np.dtype('f'))
#Out: dtype('float32')

# 字符编码来指定双精度浮点数类型
print("In: dtype('d')")
print(np.dtype('d'))
#Out: dtype('float64')

# 两个字符作为参数传给数据类型的构造函数, 第一个字符表示数据类型,
# 第二个字符表示该类型在内存中占用的字节数(2、4、8分别代表精度为16、32、64位的浮点数)
print("In: dtype('f8')")
print(np.dtype('f8'))
#Out: dtype('float64')


print("In: dtype('Float64')")
print(np.dtype('Float64'))
#Out: dtype('float64')

print(np.sctypeDict.keys())

执行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
$ python3 dtypeconstructors.py 
In: dtype(float)
float64
In: dtype('f')
float32
In: dtype('d')
float64
In: dtype('f8')
float64
In: dtype('Float64')
float64
dict_keys(['ubyte', 1, 'cdouble', 3, 4, 5, 6, 7, 8, 'I', 'longdouble', 11, 12, 13, 'p', 15, 16, 17, 18, 19, 20, 21, 22, 23, 'uintp', 'int16', 'bytes0', 0, 'singlecomplex', 'u1', 'u8', 'e', 'str0', 'longcomplex', 'complex_', 'ulonglong', 'D', 'timedelta64', 'object_', 'h', 'unicode', 'byte', 'bool_', 'datetime64', 'cfloat', 'Void0', 10, 'clongfloat', 'str', 'complex128', 'S', 2, 'bool8', 'P', 'Timedelta64', 'float128', 'i8', 'F', 'complex', 'uint', 14, 'b', 'int64', 'int32', '?', 'g', 'q', 'bytes_', 'a', 'UInt64', 'bytes', 9, 'M8', 'void0', 'uint64', 'f8', 'str_', 'double', 'float', 'float64', 'u4', 'longlong', 'int_', 'void', 'c32', 'Str0', 'long', 'int8', 'intp', 'l', 'B', 'V', 'clongdouble', 'object', 'string_', 'Q', 'intc', 'Datetime64', 'object0', 'Int32', 'short', 'int0', 'O', 'G', 'm8', 'UInt16', 'U', 'i', 'Complex32', 'Int16', 'c16', 'Float64', 'u2', 'Int64', 'float_', 'c8', 'b1', 'Bool', 'uint32', 'H', 'm', 'longfloat', 'Float16', 'f16', 'csingle', 'float16', 'uint16', 'Int8', 'f2', 'half', 'unicode_', 'Float32', 'complex256', 'd', 'i2', 'int', 'Object0', 'Float128', 'float32', 'uintc', 'i4', 'Bytes0', 'UInt32', 'single', 'L', 'Complex128', 'Complex64', 'uint8', 'f', 'uint0', 'f4', 'UInt8', 'bool', 'complex64', 'ushort', 'i1', 'M'])

record.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates the NumPy record data type.
#
# Run from the commandline with 
#
#  python record.py
print("In: t = dtype([('name', numpy.str_, 40), ('numitems', numpy.int32), ('price', numpy.float32)])")
t = np.dtype([('name', np.str_, 40), ('numitems', np.int32), ('price', np.float32)])
print(t)
#Out: dtype([('name', '|S40'), ('numitems', '<i4'), ('price', '<f4')])

print("In: t['name']")
print(t['name'])
#Out: dtype('|S40')


print("In: itemz = array([('Meaning of life DVD', 42, 3.14), ('Butter', 13, 2.72)], dtype=t)")
itemz = np.array([('Meaning of life DVD', 42, 3.14), ('Butter', 13, 2.72)], dtype=t)


print("In: itemz[1]")
print(itemz[1])
#Out: ('Butter', 13, 2.7200000286102295)

执行结果:

1
2
3
4
5
6
7
8
$ python3 record.py 
In: t = dtype([('name', numpy.str_, 40), ('numitems', numpy.int32), ('price', numpy.float32)])
[('name', '<U40'), ('numitems', '<i4'), ('price', '<f4')]
In: t['name']
<U40
In: itemz = array([('Meaning of life DVD', 42, 3.14), ('Butter', 13, 2.72)], dtype=t)
In: itemz[1]
('Butter', 13, 2.72)

在用 array 函数创建数组时,如果没有在参数中指定数据类型,将默认为浮点数类型。创建自定义数据类型的数组,就必须在参数中指定数据类型,否则将触发 TypeError错误。

  • dtype 类的属性

dtypeattributes2.py

 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
32
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author:    china-testing#126.com 技术支持qq群:630011153
# CreateDate: 2018-04-12
import numpy as np

# Chapter2 Beginning with NumPy fundamentals
#
# Demonstrates the NumPy 
# dtype attributes
#
# Run from the commandline with 
#
#  python dtypeattributes2.py
print("In: t = dtype('Float64')")
t = np.dtype('Float64')

# 获取数据类型的字符编码
print("In: t.char")
print(t.char)
#Out: 'd'

# type 属性对应于数组元素的数据类型
print("In: t.type")
print(t.type)
#Out: <type 'numpy.float64'>

# 大端序(big-endian)和小端序(little-endian)。大端序是将最高位字节存储在最低的内存
#地址处,用 > 表示;与之相反,小端序是将最低位字节存储在最低的内存地址处,用 < 表示:
print("In: t.str")
print(t.str)
#Out: '<f8'

执行结果:

1
2
3
4
5
6
7
8
$ python3 dtypeattributes2.py 
In: t = dtype('Float64')
In: t.char
d
In: t.type
<class 'numpy.float64'>
In: t.str
<f8

索引和切片

slicing1d.py

 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
32
33
34
35
36
37
38
import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates one dimensional arrays slicing.
#
# Run from the commandline with 
#
#  python slicing1d.py

print("In: a = arange(9)")
a = np.arange(9)

print("In: a[3:7]")
print(a[3:7])
#Out: array([3, 4, 5, 6])

print("In: a[:7:2]")
print(a[:7:2])
#Out: array([0, 2, 4, 6])

print("In: a[::-1]")
print(a[::-1])
#Out: array([8, 7, 6, 5, 4, 3, 2, 1, 0])

print("In: s = slice(3,7,2)")
s = slice(3,7,2)
print("In: a[s]")
print(a[s])
#Out: array([3, 5])


print("In: s = slice(None, None, -1)")
s = slice(None, None, -1)

print("In: a[s]")
print(a[s])
#Out: array([8, 7, 6, 5, 4, 3, 2, 1, 0])

执行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$ python3 slicing1d.py 
In: a = arange(9)
In: a[3:7]
[3 4 5 6]
In: a[:7:2]
[0 2 4 6]
In: a[::-1]
[8 7 6 5 4 3 2 1 0]
In: s = slice(3,7,2)
In: a[s]
[3 5]
In: s = slice(None, None, -1)
In: a[s]
[8 7 6 5 4 3 2 1 0]

slicing.py

  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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates multi dimensional arrays slicing.
#
# Run from the commandline with 
#
#  python slicing.py
print("In: b = arange(24).reshape(2,3,4)")
b = np.arange(24).reshape(2,3,4)

print("In: b.shape")
print(b.shape)
#Out: (2, 3, 4)

print("In: b")
print(b)
#Out: 
#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]]])


print("In: b[0,0,0]")
print(b[0,0,0])
#Out: 0


print("In: b[:,0,0]")
print(b[:,0,0])
#Out: array([ 0, 12])

print("In: b[0]")
print(b[0])
#Out: 
#array([[ 0,  1,  2,  3],
#       [ 4,  5,  6,  7],
#       [ 8,  9, 10, 11]])


print("In: b[0, :, :]")
print(b[0, :, :])
#Out: 
#array([[ 0,  1,  2,  3],
#       [ 4,  5,  6,  7],
#       [ 8,  9, 10, 11]])

print("In: b[0, ...]")
print(b[0, ...])
#Out: 
#array([[ 0,  1,  2,  3],
#       [ 4,  5,  6,  7],
#       [ 8,  9, 10, 11]])


print("In: b[0,1]")
print(b[0,1])
#Out: array([4, 5, 6, 7])


print("In: b[0,1,::2]")
print(b[0,1,::2])
#Out: array([4, 6])


print("In: b[...,1]")
print(b[...,1])
#Out: 
#array([[ 1,  5,  9],
#       [13, 17, 21]])

print("In: b[:,1]")
print(b[:,1])
#Out: 
#array([[ 4,  5,  6,  7],
#       [16, 17, 18, 19]])

print("In: b[0,:,1]")
print(b[0,:,1])
#Out: array([1, 5, 9])

print("In: b[0,:,-1]")
print(b[0,:,-1])
#Out: array([ 3,  7, 11])

print("In: b[0,::-1, -1]")
print(b[0,::-1, -1])
#Out: array([11,  7,  3])

print("In: b[0,::2,-1]")
print(b[0,::2,-1])
#Out: array([ 3, 11])

print("In: b[::-1]")
print(b[::-1])
#Out: 
#array([[[12, 13, 14, 15],
#        [16, 17, 18, 19],
#        [20, 21, 22, 23]],
#
#       [[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11]]])


print("In: s = slice(None, None, -1)")
s = slice(None, None, -1)
print("In: b[(s, s, s)]")
print(b[(s, s, s)])
#Out: 
#array([[[23, 22, 21, 20],
#        [19, 18, 17, 16],
#        [15, 14, 13, 12]],
#
#       [[11, 10,  9,  8],
#        [ 7,  6,  5,  4],
#        [ 3,  2,  1,  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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
$ python3 slicing.py 
In: b = arange(24).reshape(2,3,4)
In: b.shape
(2, 3, 4)
In: b
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
In: b[0,0,0]
0
In: b[:,0,0]
[ 0 12]
In: b[0]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
In: b[0, :, :]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
In: b[0, ...]
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]
In: b[0,1]
[4 5 6 7]
In: b[0,1,::2]
[4 6]
In: b[...,1]
[[ 1  5  9]
 [13 17 21]]
In: b[:,1]
[[ 4  5  6  7]
 [16 17 18 19]]
In: b[0,:,1]
[1 5 9]
In: b[0,:,-1]
[ 3  7 11]
In: b[0,::-1, -1]
[11  7  3]
In: b[0,::2,-1]
[ 3 11]
In: b[::-1]
[[[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]

 [[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]]
In: s = slice(None, None, -1)
In: b[(s, s, s)]
[[[23 22 21 20]
  [19 18 17 16]
  [15 14 13 12]]

 [[11 10  9  8]
  [ 7  6  5  4]
  [ 3  2  1  0]]]

修改维度

shapemanipulation.py

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author:    china-testing#126.com 技术支持qq群:630011153
# CreateDate: 2018-04-12

import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates multi dimensional arrays slicing.
#
# Run from the commandline with 
#
#  python shapemanipulation.py
print("In: b = arange(24).reshape(2,3,4)")
b = np.arange(24).reshape(2,3,4)

print("In: b")
print(b)
#Out: 
#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]]])

print("In: b.ravel()")
print(b.ravel())
#Out: 
#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 函数会请求分配内存来保存结果,而 ravel 函数只是返回数组的一个视图(view)
print("In: b.flatten()")
print(b.flatten())
#Out: 
#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])

print("In: b.shape = (6,4)")
b.shape = (6,4)

print("In: b")
print(b)
#Out: 
#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]])

print("In: b.transpose()")
print(b.transpose())
#Out: 
#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 resize 和 reshape 函数的功能一样
print("In: b.resize((2,12))")
b.resize((2,12))

print("In: b")
print(b)
#Out: 
#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]])

执行结果:

 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
$ python3 shapemanipulation.py
In: b = arange(24).reshape(2,3,4)
In: b
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
In: b.ravel()
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
In: b.flatten()
[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23]
In: b.shape = (6,4)
In: b
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
In: b.transpose()
[[ 0  4  8 12 16 20]
 [ 1  5  9 13 17 21]
 [ 2  6 10 14 18 22]
 [ 3  7 11 15 19 23]]
In: b.resize((2,12))
In: b
[[ 0  1  2  3  4  5  6  7  8  9 10 11]
 [12 13 14 15 16 17 18 19 20 21 22 23]]

数组组合

NumPy数组有水平组合、垂直组合和深度组合等多种组合方式,我们将使用 vstack 、dstack 、 hstack 、 column_stack 、 row_stack 以及 concatenate 函数来完成数组的组合。

stacking.py

  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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author:    china-testing#126.com 技术支持qq群:630011153
# CreateDate: 2018-04-12

import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates array stacking.
#
# Run from the commandline with 
#
#  python stacking.py
print("In: a = arange(9).reshape(3,3)")
a = np.arange(9).reshape(3,3)

print("In: a")
print(a)
#Out: 
#array([[0, 1, 2],
#       [3, 4, 5],
#       [6, 7, 8]])

print("In: b = 2 * a")
b = 2 * a

print("In: b")
print(b)
#Out: 
#array([[ 0,  2,  4],
#       [ 6,  8, 10],
#       [12, 14, 16]])

# 水平组合
print("In: hstack((a, b))")
print(np.hstack((a, b)))
#Out: 
#array([[ 0,  1,  2,  0,  2,  4],
#       [ 3,  4,  5,  6,  8, 10],
#       [ 6,  7,  8, 12, 14, 16]])

print("In: concatenate((a, b), axis=1)")
print(np.concatenate((a, b), axis=1))
#Out: 
#array([[ 0,  1,  2,  0,  2,  4],
#       [ 3,  4,  5,  6,  8, 10],
#       [ 6,  7,  8, 12, 14, 16]])

# 垂直组合
print("In: vstack((a, b))")
print(np.vstack((a, b)))
#Out: 
#array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 0,  2,  4],
#       [ 6,  8, 10],
#       [12, 14, 16]])

# 
print("In: concatenate((a, b), axis=0)")
print(np.concatenate((a, b), axis=0))
#Out: 
#array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 0,  2,  4],
#       [ 6,  8, 10],
#       [12, 14, 16]])

# 深度组合
print("In: dstack((a, b))")
print(np.dstack((a, b)))
#Out: 
#array([[[ 0,  0],
#        [ 1,  2],
#        [ 2,  4]],
#
#       [[ 3,  6],
#        [ 4,  8],
#        [ 5, 10]],
#
#       [[ 6, 12],
#        [ 7, 14],
#        [ 8, 16]]])

# 列组合
print("In: oned = arange(2)")
oned = np.arange(2)

print("In: oned")
print(oned)
#Out: array([0, 1])

print("In: twice_oned = 2 * oned")
twice_oned = 2 * oned

print("In: twice_oned")
print(twice_oned)
#Out: array([0, 2])


print("In: column_stack((oned, twice_oned))")
print(np.column_stack((oned, twice_oned)))
#Out: 
#array([[0, 0],
#       [1, 2]])

print("In: column_stack((a, b))")
print(np.column_stack((a, b)))
#Out: 
#array([[ 0,  1,  2,  0,  2,  4],
#       [ 3,  4,  5,  6,  8, 10],
#       [ 6,  7,  8, 12, 14, 16]])

print("In: column_stack((a, b)) == hstack((a, b))")
print(np.column_stack((a, b)) == np.hstack((a, b)))
#Out: 
#array([[ True,  True,  True,  True,  True,  True],
#       [ True,  True,  True,  True,  True,  True],
#       [ True,  True,  True,  True,  True,  True]], dtype=bool)


# 行组合
# 对于两个一维数组,将直接层叠起来组合成一个二维数组。
print("In: row_stack((oned, twice_oned))")
print(np.row_stack((oned, twice_oned)))
#Out: 
#array([[0, 1],
#       [0, 2]])

# 对于二维数组, row_stack 与 vstack 的效果是相同的:
print("In: row_stack((a, b))")
print(np.row_stack((a, b)))
#Out: 
#array([[ 0,  1,  2],
#       [ 3,  4,  5],
#       [ 6,  7,  8],
#       [ 0,  2,  4],
#       [ 6,  8, 10],
#       [12, 14, 16]])

print("In: row_stack((a,b)) == vstack((a, b))")
print(np.row_stack((a,b)) == np.vstack((a, b)))
#Out: 
#array([[ True,  True,  True],
#       [ True,  True,  True],
#       [ True,  True,  True],
#       [ True,  True,  True],
#       [ True,  True,  True],
#       [ True,  True,  True]], dtype=bool)

执行结果:

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
andrew@andrew-PowerEdge-T630:~/code/china-testing/python3_libraries/numpy/Chapter2$ python3 stacking.py 
In: a = arange(9).reshape(3,3)
In: a
[[0 1 2]
 [3 4 5]
 [6 7 8]]
In: b = 2 * a
In: b
[[ 0  2  4]
 [ 6  8 10]
 [12 14 16]]
In: hstack((a, b))
[[ 0  1  2  0  2  4]
 [ 3  4  5  6  8 10]
 [ 6  7  8 12 14 16]]
In: concatenate((a, b), axis=1)
[[ 0  1  2  0  2  4]
 [ 3  4  5  6  8 10]
 [ 6  7  8 12 14 16]]
In: vstack((a, b))
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 0  2  4]
 [ 6  8 10]
 [12 14 16]]
In: concatenate((a, b), axis=0)
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 0  2  4]
 [ 6  8 10]
 [12 14 16]]
In: dstack((a, b))
[[[ 0  0]
  [ 1  2]
  [ 2  4]]

 [[ 3  6]
  [ 4  8]
  [ 5 10]]

 [[ 6 12]
  [ 7 14]
  [ 8 16]]]
In: oned = arange(2)
In: oned
[0 1]
In: twice_oned = 2 * oned
In: twice_oned
[0 2]
In: column_stack((oned, twice_oned))
[[0 0]
 [1 2]]
In: column_stack((a, b))
[[ 0  1  2  0  2  4]
 [ 3  4  5  6  8 10]
 [ 6  7  8 12 14 16]]
In: column_stack((a, b)) == hstack((a, b))
[[ True  True  True  True  True  True]
 [ True  True  True  True  True  True]
 [ True  True  True  True  True  True]]
In: row_stack((oned, twice_oned))
[[0 1]
 [0 2]]
In: row_stack((a, b))
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 0  2  4]
 [ 6  8 10]
 [12 14 16]]
In: row_stack((a,b)) == vstack((a, b))
[[ True  True  True]
 [ True  True  True]
 [ True  True  True]
 [ True  True  True]
 [ True  True  True]
 [ True  True  True]]

数组分隔

splitting.py

  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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author:    china-testing#126.com 技术支持qq群:630011153
# CreateDate: 2018-04-12

import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates array splitting.
#
# Run from the commandline with 
#
#  python splitting.py
print("In: a = arange(9).reshape(3, 3)")
a = np.arange(9).reshape(3, 3)

print("In: a")
print(a)
#Out: 
#array([[0, 1, 2],
#       [3, 4, 5],
#       [6, 7, 8]])

# 水平分割
print("In: hsplit(a, 3)")
print(np.hsplit(a, 3))
#Out: 
#[array([[0],
#       [3],
#       [6]]),
# array([[1],
#       [4],
#       [7]]),
# array([[2],
#       [5],
#       [8]])]

# 垂直分割 
print("In: split(a, 3, axis=1)")
print(np.split(a, 3, axis=1))
#Out: 
#[array([[0],
#       [3],
#       [6]]),
# array([[1],
#       [4],
#       [7]]),
# array([[2],
#       [5],
#       [8]])]

# 
print("In: vsplit(a, 3)")
print(np.vsplit(a, 3))
#Out: [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]

print("In: split(a, 3, axis=0)")
print(np.split(a, 3, axis=0))
#Out: [array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]

# 深度分割 
print("In: c = arange(27).reshape(3, 3, 3)")
c = np.arange(27).reshape(3, 3, 3)

print("In: c")
print(c)
#Out: 
#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]]])

print("In: dsplit(c, 3)")
print(np.dsplit(c, 3))
#Out: 
#[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]]])]

执行结果:

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
$ python3 splitting.py 
In: a = arange(9).reshape(3, 3)
In: a
[[0 1 2]
 [3 4 5]
 [6 7 8]]
In: hsplit(a, 3)
[array([[0],
       [3],
       [6]]), array([[1],
       [4],
       [7]]), array([[2],
       [5],
       [8]])]
In: split(a, 3, axis=1)
[array([[0],
       [3],
       [6]]), array([[1],
       [4],
       [7]]), array([[2],
       [5],
       [8]])]
In: vsplit(a, 3)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]
In: split(a, 3, axis=0)
[array([[0, 1, 2]]), array([[3, 4, 5]]), array([[6, 7, 8]])]
In: c = arange(27).reshape(3, 3, 3)
In: c
[[[ 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]]]
In: 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]]])]

数组属性

arrayattributes2.py

  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
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author:    china-testing#126.com 技术支持qq群:630011153
# CreateDate: 2018-04-12

import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates ndarray attributes.
#
# Run from the commandline with 
#
#  python arrayattributes2.py
b = np.arange(24).reshape(2, 12)
print("In: b")
print(b)
#Out: 
#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]])

print("In: b.ndim")
print(b.ndim)
#Out: 2

print("In: b.size")
print(b.size)
#Out: 24

print("In: b.itemsize")
print(b.itemsize)
#Out: 8

print("In: b.nbytes")
print(b.nbytes)
#Out: 192

print("In: b.size * b.itemsize")
print(b.size * b.itemsize)
#Out: 192

print("In: b.resize(6,4)")
print(b.resize(6,4))

print("In: b")
print(b)
#Out: 
#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]])

print("In: b.T")
print(b.T)
#Out: 
#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]])

print("In: b.ndim")
print(b.ndim)
#Out: 1

print("In: b.T")
print(b.T)
#Out: array([0, 1, 2, 3, 4])


print("In: b = array([1.j + 1, 2.j + 3])")
b = np.array([1.j + 1, 2.j + 3])

print("In: b")
print(b)
#Out: array([ 1.+1.j,  3.+2.j])

print("In: b.real")
print(b.real)
#Out: array([ 1.,  3.])

print("In: b.imag")
print(b.imag)
#Out: array([ 1.,  2.])

print("In: b.dtype")
print(b.dtype)
#Out: dtype('complex128')

print("In: b.dtype.str")
print(b.dtype.str)
#Out: '<c16'


print("In: b = arange(4).reshape(2,2)")
b = np.arange(4).reshape(2,2)

print("In: b")
print(b)
#Out: 
#array([[0, 1],
#       [2, 3]])

print("In: f = b.flat")
f = b.flat

print("In: f")
print(f)
#Out: <numpy.flatiter object at 0x103013e00>

print("In: for it in f: print it")
for it in f: 
   print(it)
#0
#1
#2
#3

print("In: b.flat[2]")
print(b.flat[2])
#Out: 2


print("In: b.flat[[1,3]]")
print(b.flat[[1,3]])
#Out: array([1, 3])


print("In: b")
print(b)
#Out: 
#array([[7, 7],
#       [7, 7]])

print("In: b.flat[[1,3]] = 1")
b.flat[[1,3]] = 1

print("In: b")
print(b)
#Out: 
#array([[7, 1],
#       [7, 1]])

执行结果:

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
$ python3 arrayattributes2.py
In: b
[[ 0  1  2  3  4  5  6  7  8  9 10 11]
 [12 13 14 15 16 17 18 19 20 21 22 23]]
In: b.ndim
2
In: b.size
24
In: b.itemsize
8
In: b.nbytes
192
In: b.size * b.itemsize
192
In: b.resize(6,4)
None
In: b
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]
 [16 17 18 19]
 [20 21 22 23]]
In: b.T
[[ 0  4  8 12 16 20]
 [ 1  5  9 13 17 21]
 [ 2  6 10 14 18 22]
 [ 3  7 11 15 19 23]]
In: b.ndim
2
In: b.T
[[ 0  4  8 12 16 20]
 [ 1  5  9 13 17 21]
 [ 2  6 10 14 18 22]
 [ 3  7 11 15 19 23]]
In: b = array([1.j + 1, 2.j + 3])
In: b
[1.+1.j 3.+2.j]
In: b.real
[1. 3.]
In: b.imag
[1. 2.]
In: b.dtype
complex128
In: b.dtype.str
<c16
In: b = arange(4).reshape(2,2)
In: b
[[0 1]
 [2 3]]
In: f = b.flat
In: f
<numpy.flatiter object at 0x182a3c0>
In: for it in f: print it
0
1
2
3
In: b.flat[2]
2
In: b.flat[[1,3]]
[1 3]
In: b
[[0 1]
 [2 3]]
In: b.flat[[1,3]] = 1
In: b
[[0 1]
 [2 1]]

数组转换

arrayconversion.py

 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
32
33
34
35
36
37
38
39
40
41
42
43
import numpy as np

# Chapter 2 Beginning with NumPy fundamentals
#
# Demonstrates the NumPy record data type.
#
# Run from the commandline with 
#
#  python3 arrayconversion.py
b = np.array([ 1.+1.j,  3.+2.j])
print("In: b")
print(b)
#Out: array([ 1.+1.j,  3.+2.j])

print("In: b.tolist()")
print(b.tolist())
#Out: [(1+1j), (3+2j)]

print("In: b.tostring()")
print(b.tostring())
#Out: '\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x00@'

print("In: fromstring(b'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x00@', dtype=complex)")
print(np.fromstring(b'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x00@', dtype=complex))
#Out: array([ 1.+1.j,  3.+2.j]

print("In: fromstring('20:42:52',sep=':', dtype=int)")
print(np.fromstring('20:42:52',sep=':', dtype=int))
#Out: array([20, 42, 52])

print("In: b")
print(b)
#Out: array([ 1.+1.j,  3.+2.j])

print("In: b.astype(int)")
print(b.astype(int))
#/usr/local/bin/ipython:1: ComplexWarning: Casting complex values to real discards the imaginary part
#  #!/usr/bin/python
#Out: array([1, 3])

print("In: b.astype('complex')")
print(b.astype('complex'))
#Out: array([ 1.+1.j,  3.+2.j])

执行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
$ python3 arrayconversion.py
In: b
[1.+1.j 3.+2.j]
In: b.tolist()
[(1+1j), (3+2j)]
In: b.tostring()
b'\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\xf0?\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x00@'
In: fromstring(b'ð?ð@@', dtype=complex)
[1.+1.j 3.+2.j]
In: fromstring('20:42:52',sep=':', dtype=int)
[20 42 52]
In: b
[1.+1.j 3.+2.j]
In: b.astype(int)
arrayconversion.py:36: ComplexWarning: Casting complex values to real discards the imaginary part
  print(b.astype(int))
[1 3]
In: b.astype('complex')
[1.+1.j 3.+2.j]

links