1. Numpy介绍和运行速度的比较
Numpy是Python的一个库,提供了Python高性能的数组与矩阵运算处理的能力。本身是将Python的运算,放到了C语言上运算。
import numpy as np
def squares(values):
result = []
for v in values:
result.append(v * v)
return result
#use Python
to_square = range(10000)
%timeit squares(to_square)
#Answer: 2.57 ms ± 537 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
#use Numpy
array_to_square = np.arange(0 , 10000)
%timeit array_to_square ** 2
#Answer: 16.7 µs ± 1.02 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
1毫秒是1000微秒,很明显的看出,在利用Numpy下的数据运行速度很快。
2.ndarray介绍
ndarray是Numpy中用来表示数组用的。
注意最后的的地方,np.size(x2 , 0)代表输出行 , 而np.size(x2 , 1)代表输出列.
import Numpy as np
x = np.array([1 , 2 , 3 , 4 , 5])
print(type(x))#元素类型
print(x.ndim) #维度
print(x.shape) #形状:(5列) , 先说列再说行,往后顶
print(x.size) #元素个数
print(x.itemsize) #存储字节个数
print(x.data)#查看元素的存储位置
y = np.array([[1 , 2 , 3 , 4 , 5] , [6 , 7 , 8 , 9 , 10] , [11 , 12 , 13 , 14 , 15]]) #形状:(3行 , 5列)
print(y.ndim)
print(y.shape)
print(y.size)
print(y.itemsize)
print(y.data)
x2 = np.arange(0 , 12).reshape(4 , 3)
print(x2)
print(np.size(x2 , 0))#输出行
print(np.size(x2 , 1))#输出列
3.Boolean Selection 布尔选择器
布尔选择器是用来对数据进行切片处理的,包括了Slice,Reshape等操作。其实就是对于数组的一个基本的操作。
print(x)
mask = x < 3
print(mask)
print(x[mask])
print(np.sum)
'''
[1 2 3 4 5]
[ True True False False False]
[1 2]
<function sum at 0x000001D6C15DAB70>
'''
a1 = np.arange(9).reshape(3 , 3)
a2 = np.arange(9 , 0 , -1).reshape(3 , 3)
print(a1)
print(a2)
print(a1 < a2)
'''
[[0 1 2]
[3 4 5]
[6 7 8]]
[[9 8 7]
[6 5 4]
[3 2 1]]
[[ True True True]
[ True True False]
[False False False]]
'''
y = np.arange(9).reshape(3 , 3)
reshaped = y.reshape(np.size(y))
reveled = y.ravel()
f = y.flatten()
print(y)
print(reshaped)#[0 1 2 3 4 5 6 7 8]
print(reveled)#[0 1 2 3 4 5 6 7 8]
print(f)#[0 1 2 3 4 5 6 7 8]
4.合并
ndarray数组支持向量化的运算。
1.注意hstack传入的数据是元组。
#Combination
a = np.arange(9).reshape(3 , 3)
b = (a + 1) * 10
b
'''
array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
'''
np.hstack((a , b))#水平合并
np.concatenate((a , b) , axis = 1)#水平合并
'''
array([[ 0, 1, 2, 10, 20, 30],
[ 3, 4, 5, 40, 50, 60],
[ 6, 7, 8, 70, 80, 90]])
'''
np.vstack((a , b))#竖直合并
np.concatenate((a , b) , axis = 0)#竖直合并
'''
Out[27]:
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
'''