8.2.1、Python__numpy库的使用,numpy库是安装,并进行数据的清洗计算

1、numpy

numpy 是一个专门用于矩阵化运算、科学计算的开源Python(用于科学计算的库)

2、安装numpy

在下面控制台直接下载 pip install numpy
下载运行环境:pip install jupyter notebook
进入:jupyter notebook

3、使用jupyter notebook操作numpy 进行科学计算

(1)构建矩阵array

import numpy as np
n1 = np.array([[1,2,3],[4,5,6]])
n1.max()	#直接调方法进行使用

(2)类型转换:astype

np3 = np.array(['1','2','3'])	#字符串类型不能进行操作分析
np3 = np3.astype(int)		#转换

(3)索引:切片索引和布尔索引
1)切片索引
—行的方向(上下),列的方向(左右)
切片:以,分割两个部分,左边行,右边列,分别切片(该省的都可以省,如步长等)

np1 = np.array([[1,2,3],[4,5,6]])		#取2,3,5,6
np1[0:2:1,1:3:1]
示例:建立矩阵
np2 = np.array([
[0,1,2,3,4,5],
[10,11,12,13,14,15],
[20,21,22,23,24,25],
[30,31,32,33,34,35],
[40,41,42,43,44,45],
[50,51,52,53,54,55]
])
np2.shape		#查看

在这里插入图片描述

橙色:np2[0,3:5]
红色:np2[::,2]
绿色:np2[2::2,0::2]
蓝色:np2[4:,4:]	#取到最后一行可以省略

在这里插入图片描述

蓝色:np2[3::,[0,2,5]]	#用[]直接写出哪几列
橙色:np2[(0,1,2,3,4),(1,2,3,4,5)]	#使用元组一一匹配
红色:np2[[0,2,5],2]	#或
    boolNd = np.array([1,0,1,0,0,1],dtype=np.bool_)
    np2[boolNd,2]	#布尔索引

2)布尔索引
—通过添加条件判断数组中每个值的真/假转为布尔值再对原数组进行索引,为真 True 时会被抽取出来
#取出大于22的值

np2>22		#构建布尔矩阵
np2[np2>22]	#作为索引

(4)对位运算
—相应位置上进行运算+ - * /

#想要实现矩阵的运算调方法dot
#上一个矩阵的列等于下一个矩阵的行才可以运算(矩阵运算法则)
nd1.dot(nd3)
(5)随机数

import random
random.random()	#随机产生一个【0,1)数字
random.randint(1,5)		#随机产生一个【1,5)整数

#numpy中的随机数产生
from numpy import random
random.rand(4,5)		#产生一个4*5的numpy

猜你喜欢

转载自blog.csdn.net/nerer/article/details/121193261