导入Numpy
import numpy as np
读取数据
world_alcohol = np.genfromtxt("world_alcohol.txt", delimiter=",", dtype = str)
print(world_alcohol)
>[['Year' 'WHO region' 'Country' 'Beverage Types' 'Display Value']
['1986' 'Western Pacific' 'Viet Nam' 'Wine' '0']
['1986' 'Americas' 'Uruguay' 'Other' '0.5']
...
['1987' 'Africa' 'Malawi' 'Other' '0.75']
['1989' 'Americas' 'Bahamas' 'Wine' '1.5']
['1985' 'Africa' 'Malawi' 'Spirits' '0.31']]
genfromtxt参数:
文本分隔符 delimiter = ","
数据读取类型 dtype = str
跳过头行数 skip_header = 1
定义矩阵
vector = np.array([1, 2, 3, 4])
matrix = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
打印结构
print(vector.shape)
print(matrix.shape)
>(4,)
(2, 4)
array中数据类型为同一种类型
计算
判断
#判断
vector = np.array([1,3,5,4])
a = vector == 1
print(a)
[ True False False False]
b =vector < 5
print(vector[b])
>[1 3 4]
matrix = np.array([[1,2,3],[5,15,20],[25,30,35]])
second_column_15 = matrix[:, 1] == 15
print(second_column_15)
print(matrix[second_column_15,:])
>[False True False]
[[ 5 15 20]]
vector = np.array([5, 15, 20 ,25])
equal_to_ten_and_five = (vector == 10) & (vector == 5)
equal_to_ten_or_five = (vector == 10) | (vector == 5)
print(equal_to_ten_and_five)
print(equal_to_ten_or_five)
>[False False False False]
[ True False False False]
vector[equal_to_ten_or_five] = 50
print(vector)
>[50 15 20 25]
类型转换
vector = np.array(["1", "2", "3", "4"])
vector = vector.astype(float)
print(vector.dtype)
print(vector)
>float64
[1. 2. 3. 4.]
求和
matrix = np.array([[1,2,3],[5,15,20],[25,30,35]])
print(matrix.sum()) #所有元素求和
print(matrix.sum(axis = 1)) #行元素求和
print(matrix.sum(axis = 0)) #列元素求和
>136
[ 6 40 90]
[31 47 58]
常用函数
变换
np.arange(15)
>array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])
a = np.arange(15).reshape(3,5)
print(a)
>[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]]
a.ndim #维度
>2
a.size #元素个数
>15
np.zeros((3,4)) #0矩阵
>array([[0., 0., 0., 0.],
[0., 0., 0., 0.],
[0., 0., 0., 0.]])
np.ones((2,3,4), dtype=np.int32) #1矩阵,整型
>array([[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]]])
np.arange(10, 30, 5) #序列
>array([10, 15, 20, 25])
随机数
np.random.random((2, 3))
>array([[0.37966439, 0.72749195, 0.65091678],
[0.7075526 , 0.83246759, 0.06179741]])
from numpy import pi
np.linspace(0,2*pi,10) #0-2pi平均取10个值
>array([0. , 0.6981317 , 1.3962634 , 2.0943951 , 2.7925268 ,
3.4906585 , 4.1887902 , 4.88692191, 5.58505361, 6.28318531])
矩阵计算
A = np.array([[1, 1],
[0, 1]])
B = np.array([[2, 0],
[3, 4]])
print(A*B) #元素对应位置相乘
>[[2 0]
[0 4]]
print(A.dot(B)) #矩阵乘法
print(np.dot(A, B)) #矩阵乘法
>[[5 4]
[3 4]]
np.floor() #向下取整
np.ravel() #矩阵转向量
A.T #转置
A = np.floor(10*np.random.random((2,2)))
B = np.floor(10*np.random.random((2,2)))
print(A)
print(B)
>[[2. 8.]
[9. 6.]]
[[0. 3.]
[3. 8.]]
print(np.hstack((A,B))) #横向拼接
>[[2. 8. 0. 3.]
[9. 6. 3. 8.]]
print(np.vstack((A,B)))#纵向拼接
>[[2. 8.]
[9. 6.]
[0. 3.]
[3. 8.]]