1、打开txt文档
示例代码:
import numpy world_alcohol=numpy.genfromtxt("E:\\学习\\python机器学习\\机器学习课件\\3个python库代码数据\\numpy\\world_alcohol.txt",delimiter=",",dtype=str) print(type(world_alcohol)) print(world_alcohol) print(help(numpy.genfromtxt))
其中:"E:\\学习\\python机器学习\\机器学习课件\\3个python库代码数据\\numpy\\world_alcohol.txt"表示文件的路径,如果文件与代码在同一个位置,直接写文件名称即可
delimiter=","表示文件如何分割,在此例子中表示以“,”来分割文件
dtype=str表示传入的文件格式,在例子中表示以字符串类型来传入
skip_header=1表示
2、array的维度查询
示例代码:
vector=numpy.array([1,2,3,4]) print(vector.shape) matrix=numpy.array([[5,10,15],[20,25,30]]) print(matrix.shape)
vector.dtype表示该array的类型:如int32、float64等
matrix.shape表示显示该array的维度,即行数和列数。
3、array的数据提取
示例代码:
uruguay_other_1986=world_alcohol[1,4] third_country=world_alcohol[2,2] print (uruguay_other_1986) print (third_country)
uruguay_other_1986=world_alcohol[1,4]表示提取第一行第4列的值
示例代码:
vector=numpy.array([5,10,15,20]) print(vector[:3])
print(vector[:3])表示提取从0-2的值
示例代码:
matrix=numpy.array([[5,10,15],[20,25,30],[35,40,45]]) print(matrix[:,0:2])
print(matrix[:,0:2])表示提取所有行的第0,1列数据
4、array的计算
示例代码:
import numpy vector=numpy.array([5,10,15,20]) vector==10
array([False, True, False, False], dtype=bool) vector==10表示对array中的所有数进行是否等于10 的判断示例代码:
vector=numpy.array([5,10,15,20,25]) equal_to_ten=(vector==10) print(equal_to_ten) print(vector[equal_to_ten])
print(vector[equal_to_ten])表示通过布尔类型进行索引,并返回True的值
示例代码:
matrix=numpy.array([[5,10,15],[20,25,30],[35,40,45]]) second_column_25=(matrix[:,1]==25) print(second_column_25) print(matrix[:2,second_column_25])
[False True False] [[10] [25]] print(matrix[:2,second_column_25])表示返回0、1行的second_column_25值为True的结果 5、array中&和|的操作 示例代码: import numpy vector=numpy.array([5,10,15,20]) equal_to_ten_and_five=(vector==10)&(vector==5) print(equal_to_ten_and_five)