python的numpy库的学习
- numpy库中关于矩阵的知识
- numpy.genfromtxt学习
import numpy as np
world_alcohol=np.genfromtxt("C:/Users/liuju/OneDrive/Desktop/liu.txt",str)
print(type(world_alcohol))
print(world_alcohol)
print(help(np.genfromtxt))
3.python 科学计算:getfromtex函数详解
4.在数组中判断值是否相等
matrix=np.array([[5,15,25,10],[5,15,20,10],[5,15,20,10],[5,15,20,10]])
mt=(matrix[:,2]==25)
print(mt)
print(matrix[mt])#mt代表是行数
结果输出:
[ True False False False]
[[ 5 15 25 10]]
5.&和|
vector=np.array([5,5,10,10])
qt=(vector==10)&(vector==5)
print(qt)
结果输出:
[False False False False]
vector=np.array([5,5,10,10])
qt=(vector==10)|(vector==5)
print(qt)
结果输出:
[ True True True True]
6.数值类型转换
vector=np.array([5,5,10,'10'])
print(vector.dtype)
print(vector)
vector=vector.astype(float)#数据类型转换
print(vector.dtype)
print(vector)
结果输出:
<U11
[‘5’ ‘5’ ‘10’ ‘10’]
float64
[ 5. 5. 10. 10.]
7.最小值
vector.min()#最小值
8.求和(列和行)
matrix.sum(axis=1)#按类求和
结果输出:
array([55, 50, 50, 50])
matrix.sum(axis=0)#按行求和
结果输出:
array([20, 60, 85, 40])
9.print(np.arange(15))
输出结果:[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
np.arange(0,2,0.3)
输出结果:array([0. , 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])
from numpy import pi#调用pai需要import从numpy中提取
np.linspace(0,2*pi,100)#数组从1到2*pi中取100个
11
A=np.floor(10*np.random.random((3,4)))#向下取整
print(A)
print(A.shape)
print(A.ravel())#变为向量
#矩阵变形的两种方式
A.shape=(6,2)
A.reshape(3,4)
A.reshape(3,-1)#-1代表随便计算
a=np.floor(10*np.random.random((2,12)))
np.hsplit(a,3)#竖着切3等分
输出结果:
[array([[8., 8., 2., 0.],
[8., 7., 3., 4.]]),
array([[5., 3., 9., 0.],
[3., 5., 1., 6.]]),
array([[0., 3., 3., 6.],
[5., 3., 8., 3.]])]
print(np.hsplit(a,(3,4)))#在第3列和第四列切
输出结果:
[array([[4., 2., 5.],
[4., 5., 9.]]), array([[8.],
[8.]]), array([[5., 9., 6., 4., 1., 8., 0., 5.],
[7., 7., 4., 0., 9., 2., 4., 5.]])]
a=np.floor(10*np.random.random((12,2)))
print(a)
np.vsplit(a,3)#横着切
Out:
[array([[0., 6.],
[8., 1.],
[1., 0.],
[0., 6.]]),
array([[4., 1.],
[0., 5.],
[7., 3.],
[9., 4.]]),
array([[9., 2.],
[0., 7.],
[7., 8.],
[1., 2.]])]