Python数据分析:Day1-numpy学习
1、numpy
numpy(Numerical Python)提供了python对多维数组对象的支持:ndarray,具有矢量运算能力,快速、节省空间。numpy支持高级大量的维度数组与矩阵运算,此外也针对数组运算提供大量的数学函数库。
2、numpy.genfromtxt打开txt文件
实例化一个numpy.genfromtxt的对象,第一参数传要读取的文件名,第二个是分隔符,最后一个为读取的数据类型
import numpy
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",", dtype = "str")
print(type(world_alcohol))
print(world_alcohol)
输出结果:
3、numpy.array建立矩阵
#使用numpy.array方法把一个list转化为一个向量或者说是一行矩阵
vector = numpy.array([5, 10, 15, 20])
#使用numpy.array的方法把多个list转化为一个矩阵
matrix = numpy.array([[5, 10, 15], [20, 25, 30], [35, 40, 45]])
print(vector)
print(matrix)
输出结果:
4、使用ndarray.shape方法计算矩阵的维度
vector = numpy.array([1, 2, 3, 4])
print(vector.shape)
#二维矩阵的维度是一个二元组
matrix = numpy.array([[5, 10, 15], [20, 25, 30]])
print(matrix.shape)
输出结果:
(4,)
(2, 3)
5、数据类型
#构建numpy矩阵时,要求所有的数据类型为相同的数据类型。
numbers = numpy.array([1, 2, 3, 4])
numbers.dtype
print("--------------------------------------------------------")
#如果不能转换成一个同一类型的数据,则使用一个nan来标记无法识别的数据类型。
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",")
print(world_alcohol)
输出结果:
dtype(‘int32’)
[[ nan nan nan nan nan]
[1.986e+03 nan nan nan 0.000e+00]
[1.986e+03 nan nan nan 5.000e-01]
…
[1.987e+03 nan nan nan 7.500e-01]
[1.989e+03 nan nan nan 1.500e+00]
[1.985e+03 nan nan nan 3.100e-01]]
6、numpy索引
world_alcohol = numpy.genfromtxt("world_alcohol.txt", delimiter=",", dtype="U75", skip_header=1)
#取第二行第五个数据。
uruguay_other_1986 = world_alcohol[1,4]
#qu
third_country = world_alcohol[2,2]
print(uruguay_other_1986)
print(third_country)
输出结果:
0.5
Cte d’Ivoire
7、numpy切片
1)向量切片
vector = numpy.array([5, 10, 15, 20])
print(vector[0:3])
输出结果:
[ 5 10 15]
2)矩阵切片
可以使用下标切片
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[:,1])
输出结果:
[10 25 40]
3)矩阵多列切片
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[:,0:2])
输出结果:
[[ 5 10]
[20 25]
[35 40]]
3)矩阵多行多列切片
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[1:3,0:2])
输出结果:
[[20 25]
[35 40]]
8、改变矩阵的维度
matrix = numpy.array([
[5, 10, 15],
[20, 25, 30],
[35, 40, 45]
])
print(matrix[:,0:2])
print(matrix[1:3,0:2])
输出结果:
[[ 5 10]
[20 25]
[35 40]]
[[20 25]
[35 40]]