说明:个人学习记录,仅供参考。
操作系统:window10 x64
IDE:Pycharm 2017.2.2
Python版本:3.6.2
接上篇
1、创建数组、判断数组元素类型
import numpy as np
a = np.array([1, 2, 3, 4])
# int32 整数类型
print(a.dtype)
2、创建数组时指定数组元素类型、数据类型转换
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
'''
[[1 2 3]
[4 5 6]
[7 8 9]]
'''
print(a)
b = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype='str')
'''
[['1' '2' '3']
['4' '5' '6']
['7' '8' '9']]
'''
print(b)
# 数据类型转换:这里是str转为了int
'''
[[1 2 3]
[4 5 6]
[7 8 9]]
'''
c = b.astype(int)
print(c)
数组中元素的数据类型有:
- int:int16、int32、int64
- bool:True、False
- float:float16、float32、float64
- string:string、unicode
3、查询矩阵的大小
import numpy as np
a = np.array([1, 2, 3])
# (3,)
print(a.shape)
b = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
# (2, 4):2行4列的二维数组
print(b.shape)
3、使用shape完成数组变形
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])
# (4, 3)
print(a.shape)
a.shape = (6, 2)
# (6, 2)
print(a.shape)
'''
[[ 1 2]
[ 3 4]
[ 5 6]
[ 7 8]
[ 9 10]
[11 12]]
'''
print(a)
注意这里数组元素在内存中的位置并没有改变,只是改变了数组的视图(个人理解)
4、reshape获取变形的新数组
import numpy as np
a = np.array([1, 2, 3, 4])
b = a.reshape(2, 2)
# [1 2 3 4]
print(a)
'''
[[1 2]
[3 4]]
'''
print(b)
5、数组的复制:=,其实就是引用的值给了新数组名
import numpy as np
a = np.arange(12)
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(a)
b = a
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(b)
a.shape = (3, 4)
# (3, 4)
print(b.shape)
a[a == 5] = 100
'''
[[ 0 1 2 3]
[ 4 100 6 7]
[ 8 9 10 11]]
'''
print(b)
理解:a和b都是引用,指向同一片内存区域。
6、数组的浅复制(拷贝) .view
import numpy as np
a = np.arange(12)
b = a.view()
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(b)
a.shape = (3, 4)
# (12,)
print(b.shape)
a[a == 5] = 100
# [ 0 1 2 3 4 100 6 7 8 9 10 11]
print(b)
理解:a和b是同一个数组的2种不同试图。
7、数组的神复制(拷贝) .copy
import numpy as np
a = np.arange(12)
b = a.copy()
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(b)
a.shape = (3, 4)
# (12,)
print(b.shape)
a[a == 5] = 100
# [ 0 1 2 3 4 5 6 7 8 9 10 11]
print(b)
理解:b是内存中的数组拷贝了一份,a和b是两个独立的数组了。
8、查询数组维度、元素个数
import numpy as np
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
# 数组的维度:2
print(a.ndim)
# 数组元素的个数:12
print(a.size)
9、创建0矩阵、1矩阵
import numpy as np
a = np.zeros((3, 4))
'''
[[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]
[ 0. 0. 0. 0.]]
'''
print(a)
b = np.ones((3, 4))
'''
[[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]
[ 1. 1. 1. 1.]]
'''
print(b)
10、区间内等差创建矩阵
import numpy as np
a = np.arange(10, 50, 5)
# 10到50,等差为5创建元素,包含10不包含50,也即前闭后开
# [10 15 20 25 30 35 40 45]
print(a)
11、区间内按元素个数取值
import numpy as np
# 获得0-2π之间的10各数组成的数组,注意不是随机,而是平均分
a = np.linspace(0, 2 * np.pi, 10)
# [ 0. 0.6981317 1.3962634 2.0943951 2.7925268 3.4906585 4.1887902 4.88692191 5.58505361 6.28318531]
print(a)
注意不是随机!是平均分
12、==判断数组中是否含有某个值
import numpy as np
a = np.arange(4)
# 结果为值一个对应维度、个数的bool类型的数组:[False False False True]
print(a == 3)