numpy 科学计算基础库,大型多维数组运算
- numpy当成一维或多维数组
numpy的创建
- 用np.array()创建一维或多维
- 用plt创建
- 用np的routines函数创建
import numpy as np
arr=np.array([1,2,3,4,5])
arr
np.array([[1,2,3],[4,5,6]])
array([[1, 2, 3],
[4, 5, 6]])
np.array([1,2,3,4,5])
array([1, 2, 3, 4, 5])
- 读取一张图,存入数组,改变
import matplotlib.pyplot as plt
img_arr=plt.imread('./a.jpg')
print(img_arr)
[[[255 244 82]
[255 244 82]
[255 244 82]
...
[255 244 82]
[255 244 82]
[255 244 82]]
[[255 244 82]
[255 244 82]
[255 244 82]
...
[255 244 82]
[255 244 82]
[255 244 82]]
[[255 244 82]
[255 244 82]
[255 244 82]
...
[255 244 82]
[255 244 82]
[255 244 82]]
...
[[255 244 82]
[255 244 82]
[255 244 82]
...
[255 244 82]
[255 244 82]
[255 244 82]]
[[255 244 82]
[255 244 82]
[255 244 82]
...
[255 244 82]
[255 244 82]
[255 244 82]]
[[255 244 82]
[255 244 82]
[255 244 82]
...
[255 244 82]
[255 244 82]
[255 244 82]]]
- 将一个三维数组显示成一张图片
plt.imshow(img_arr-50)
<matplotlib.image.AxesImage at 0x161b5fed808>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DDcRJUZT-1627093577689)(%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_files/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_7_1.png)]
- routines函数
- zeros()
- ones()
- linespace()
- arange()
- random()系列
np.zeros(shape=(3,4)) #0的数组
np.ones(shape=(3,4)) #1的数组
np.linspace(0,100,10) #10个等差数列
np.arange(0,100,2) #间隔为2
np.random.randint(0,100,size=(5,8))
np.random.random(size=(3,4))
array([[0.35472486, 0.33621184, 0.2888372 , 0.70616024],
[0.9317908 , 0.21829476, 0.26905074, 0.15292828],
[0.50710206, 0.6630386 , 0.8916942 , 0.9815946 ]])
#固定时间 随机因子(系统时间)固定
np.random.seed(10)
np.random.randint(0,100,size=(2,3))
array([[ 9, 15, 64],
[28, 89, 93]])
numpy的属性
- shape 形状!!
- ndim 维度
- size 长度
- dtype 类型!!
arr=np.random.randint(0,100,size=(5,4))
arr.dtype
dtype('int32')
numpy数组的索引切片
- 索引,同列表
print(arr)
arr[1]
arr[[1,3]] #取多行
[[28 74 88 9]
[15 18 80 71]
[88 11 17 46]
[ 7 75 28 33]
[84 96 88 44]]
array([[15, 18, 80, 71],
[ 7, 75, 28, 33]])
- 切片
arr[0:2] #前两行
arr[:,0:2] #前两列
arr[:,::-1]#列反转
arr[::-1] #行反转
array([[84, 96, 88, 44],
[ 7, 75, 28, 33],
[88, 11, 17, 46],
[15, 18, 80, 71],
[28, 74, 88, 9]])
- 将一张图反转
plt.imshow(img_arr[::-1,::-1,::-1])
<matplotlib.image.AxesImage at 0x161b714d2c8>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lJazDaWA-1627093577692)(%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_files/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_19_1.png)]
变形 reshape 变维度
print(arr)
arr1=arr.reshape((20,)) #多维变一维
arr1.reshape((2,10)) #一变多
[[28 74 88 9]
[15 18 80 71]
[88 11 17 46]
[ 7 75 28 33]
[84 96 88 44]]
array([[28, 74, 88, 9, 15, 18, 80, 71, 88, 11],
[17, 46, 7, 75, 28, 33, 84, 96, 88, 44]])
级联 即拼接
arr3=np.array([[1,2,3],[4,5,6]])
n_arr=arr3
np.concatenate((arr3,n_arr),axis=0) # 0列拼接 1行拼接
array([[1, 2, 3],
[4, 5, 6],
[1, 2, 3],
[4, 5, 6]])
- 图的级联 九宫格
arr_3=np.concatenate((img_arr,img_arr,img_arr),axis=1)
plt.imshow(arr_3)
arr_9=np.concatenate((arr_3,arr_3),axis=0)
plt.imshow(arr_9)
<matplotlib.image.AxesImage at 0x2b8ea7ea748>
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-fpElT80R-1627093577693)(%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_files/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_25_1.png)]
广播机制
- 将低维度广播,相加,输出形状为最大值
聚合操作
- sum max min mean平均值
arr
arr.sum(axis=1)
array([199, 184, 162, 143, 312])
常用函数
- 三角函数 sin() cos() tan()
- numpy.around(a,decimals) 返回指定数字的四舍五入值
arr.around(arr,decimals=0) #0对小数 1整数
array([[28, 74, 88, 9],
[15, 18, 80, 71],
[88, 11, 17, 46],
[ 7, 75, 28, 33],
[84, 96, 88, 44]])
统计函数
- np.amin()和np.amax(),指定方向最大最小值
- np.ptp() 最大-最小
- np.median() 中位数
- arr.std()标准差 //std=sqrt(mean((x-x.mean())**2))
- arr.var()方差
arr=np.random.randint(60,100,size=(5,3))
print(arr)
np.amin(arr,axis=1)
arr.var()
[[71 82 97]
[71 81 93]
[91 84 92]
[97 69 97]
[86 67 68]]
120.86222222222221
矩阵
- arr.T转置
- np.dot(a,b) 矩阵相乘
import numpy.matlib as matlib
matlib.empty(shape=(5,6))
matlib.ones(shape=(5,6)) #zeros
matlib.eye(n=5,M=5,k=0) #对角矩阵 n行 M列 k对角索引
matlib.identity(5) #单位矩阵
matrix([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
pandas 非数值字符串,时间序列处理
Series
- Series是一种类似一维数组的对象,由两部分组成
- values:一组数据(ndarray类型)
- index:数据索引标签
Series建立
- 由列表或numpy数组创建
- 字典创建
import pandas as pd
import numpy as np
from pandas import Series,DataFrame
s1=Series(data=[1,2,3,4,5])
s2=Series(data=np.random.randint(0,100,size=(4)))
dic={'a':1,'b':2,'c':3}
s3=Series(data=dic)
s4=Series(data=[1,2,3],index=['数学','英语','理综'])
s4
数学 1
英语 2
理综 3
dtype: int64
Series索引
- 隐式索引:数值型
- 显示索引:自定义
s4[0]
s4['数学']
s4.数学
1
Series属性
- shape
- size
- index 索引
- values 值
Series常用方法
- head(),tail() 显示前 后ntiao数据
- unique() 去重
- add() sub() mul() div()
- isnull() notnull() 空值清洗
s=Series(data=[1,2,4,2,3,1,2,6,7,1,3,4])
s.head(3)
s.unique()
s+s
s1=Series(data=[1,2,3,4],index=['a','b','c','e'])
s2=Series(data=[1,2,3,4],index=['a','d','c','f'])
s=s1+s2
s_b=s.notnull()
s[s_b]
a 2.0
c 6.0
dtype: float64
DataFrame 表格型,将Series拓展得到
- index 行索引
- columns 列索引
- values 值
DataFrame的创建
- ndarray创建
- 字典创建
#查看
df.infor()
df.describe()
df.isnull().sum()
空值处理
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FgbFrLKq-1627093577695)(attachment:image.png)]
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RVZfAo7v-1627093577696)(attachment:image.png)]
密度图取代直方图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FgXBnrQC-1627093577697)(attachment:image.png)]
df=DataFrame(data=np.random.randint(0,100,size=(5,6)))
df
0 | 1 | 2 | 3 | 4 | 5 | |
---|---|---|---|---|---|---|
0 | 7 | 22 | 32 | 3 | 9 | 52 |
1 | 76 | 68 | 30 | 70 | 74 | 30 |
2 | 9 | 2 | 65 | 13 | 75 | 52 |
3 | 5 | 93 | 84 | 48 | 62 | 42 |
4 | 34 | 40 | 46 | 32 | 94 | 86 |
dic={
'姓名':['tom','jay','bobo'],
'salary':[100,120,389]
}
df=DataFrame(data=dic,index=['a','b','c'])
df
姓名 | salary | |
---|---|---|
a | tom | 100 |
b | jay | 120 |
c | bobo | 389 |
DataFrame 索引
- 行索引
- 列索引
- 元素索引
df['姓名'] #列索引
df[['姓名','salary']] #多列
df.loc['b'] #行 显示
df.iloc[0] #隐式
df.loc[['a','b']] #多行
df.iloc[2,1]
df.loc[['b','c'],'salary']
b 120
c 389
Name: salary, dtype: int64
DataFrame 切片
- 行窃
- 列切
df[0:2] #行切
df.iloc[0:2:,0:2]
姓名 | salary | |
---|---|---|
a | tom | 100 |
b | jay | 120 |
时间数据类型转化
- pd.to_datetime(col)
将某一列设为索引
- df.set_index()
dic={
'time':['2019-01-02','2011-08-22','2020-08-26'],
'salary':[182,473,599]
}
df=DataFrame(data=dic)
df
time | salary | |
---|---|---|
0 | 2019-01-02 | 182 |
1 | 2011-08-22 | 473 |
2 | 2020-08-26 | 599 |
df['time']=pd.to_datetime(df['time'])
df
time | salary | |
---|---|---|
0 | 2019-01-02 | 182 |
1 | 2011-08-22 | 473 |
2 | 2020-08-26 | 599 |
df.set_index(df['time'],inplace=True,drop=False)
df.drop(labels='time',axis=1,inplace=True)
df
salary | |
---|---|
time | |
2019-01-02 | 182 |
2011-08-22 | 473 |
2020-08-26 | 599 |
数据清洗
- dropna(axis=0) #删掉有空值的行
- df.fillna(method=‘ffill’,axis=1) #axis轴向 method=ffill(向前)/bfill(向后填充)
- df.drop_duplicates(keep=‘last’) #删掉重复行
级联(拼接)
- pd.concat((df1,df2),axis=0)
- append() 只能纵向级联
合并(数据合并)
pd.merge(df1,df2,on=‘依据条件’)
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from pandas import Series,DataFrame
df=pd.read_excel(r"糖尿病数据(202009).xlsx")
df
住院号 | 年龄 | 性别 | 血压 | 病史 | 主诉 | 出院诊断 | 尿糖值 | 胰岛素含量 | |
---|---|---|---|---|---|---|---|---|---|
0 | 57439 | 65 | 女 | 100/70 | 现病史: 发现高血糖10年 既往病史:无 | 发现高血糖10年 | 2型糖尿病 | 4+ | 8.7 |
1 | 57524 | 55 | 女 | 120/70 | 现病史:1小时前摔伤右上颌伤处疼痛 既往病史:糖尿病10年 | 右上颌外伤1小时 | 2型糖尿病 | 3+ | 11.9 |
2 | 57558 | 65 | 女 | 110/70 | 现病史:发现高血糖10年 既往病史:无 | 发现高血糖10年 | 2型糖尿病 | 4+ | 16.8 |
3 | 57573 | 71 | 女 | 120/80 | 现病史: 该患者3日来出现右侧肋部疼痛 既往病史:糖尿病病史 | 右侧肋部疼痛3日 | 2型糖尿病 | 4+ | 9.0 |
4 | 57774 | 62 | 女 | 110/70 | 现病史: 发现高血糖6月 既往病史: | 发现高血糖6月 | 2型糖尿病 | 2+ | 11.0 |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
638 | 99295 | 62 | 男 | 130/80 | 现病史: 发现血糖升高17年 既往病史:无 | 发现血糖升高17年 | 2型糖尿病 | 2+ | 18.7 |
639 | 99446 | 50 | 女 | 140/90 | 现病史:反复颜面及双下肢浮肿1月。 既往病史:境外糖尿病史10余年。 | 反复颜面及双下肢浮肿1月。 | 2型糖尿病性肾病 | 4+ | 9.3 |
640 | 99468 | 67 | 女 | 200/90 | 现病史:发现高血糖11年 既往病史:无 | 发现高血糖11年 | 2型糖尿病 | +- | 6.4 |
641 | 99632 | 66 | 女 | 140/90 | 现病史:发现血糖升高5年 既往病史:无 | 发现血糖升高5年 | 2型糖尿病 | +- | 12.1 |
642 | 99782 | 64 | 女 | 130/70 | 现病史:发现血糖升高9年 既往病史:无 | 发现血糖升高9年 | 2型糖尿病 | 3+ | 11.8 |
643 rows × 9 columns
arr=df.groupby(by='性别').count()['尿糖值']
arr
性别
女 331
男 312
Name: 尿糖值, dtype: int64
#性别和患病的关系
plt.pie(arr,labels=['Number of male patients','Number of female patients'],labeldistance=0.3,autopct='%.3f%%')
plt.title('Relationship between prevalence and gender')
Text(0.5, 1.0, 'Relationship between prevalence and gender')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KuOqcJtQ-1627093577698)(%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_files/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_68_1.png)]
brr=df.groupby(by='年龄').count()['尿糖值']
brr
年龄
26 4
28 3
30 1
32 4
34 4
35 2
36 3
37 12
39 9
40 4
41 3
42 5
43 2
44 2
45 8
46 16
47 15
48 21
49 28
50 13
51 23
52 16
53 30
54 23
55 34
56 21
57 20
58 23
59 12
60 11
61 21
62 16
63 17
64 21
65 50
66 21
67 24
68 15
69 17
70 6
71 3
72 23
73 6
74 4
75 7
76 3
78 2
79 1
80 2
81 2
84 2
92 8
Name: 尿糖值, dtype: int64
#年龄和患病的关系
plt.bar(brr.keys(),brr.values)
plt.title('Relationship between prevalence and age')
plt.xlabel('age')
plt.ylabel('numbers')
Text(0, 0.5, 'numbers')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gfH7cEuK-1627093577699)(%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_files/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_70_1.png)]
df['最高血压']=df['血压'].values
住院号 | 年龄 | 性别 | 血压 | 病史 | 主诉 | 出院诊断 | 尿糖值 | 胰岛素含量 | 最高血压 | |
---|---|---|---|---|---|---|---|---|---|---|
0 | 57439 | 65 | 女 | 100/70 | 现病史: 发现高血糖10年 既往病史:无 | 发现高血糖10年 | 2型糖尿病 | 4+ | 8.7 | 100 |
1 | 57524 | 55 | 女 | 120/70 | 现病史:1小时前摔伤右上颌伤处疼痛 既往病史:糖尿病10年 | 右上颌外伤1小时 | 2型糖尿病 | 3+ | 11.9 | 120 |
2 | 57558 | 65 | 女 | 110/70 | 现病史:发现高血糖10年 既往病史:无 | 发现高血糖10年 | 2型糖尿病 | 4+ | 16.8 | 110 |
3 | 57573 | 71 | 女 | 120/80 | 现病史: 该患者3日来出现右侧肋部疼痛 既往病史:糖尿病病史 | 右侧肋部疼痛3日 | 2型糖尿病 | 4+ | 9.0 | 120 |
4 | 57774 | 62 | 女 | 110/70 | 现病史: 发现高血糖6月 既往病史: | 发现高血糖6月 | 2型糖尿病 | 2+ | 11.0 | 110 |
for i in range(len(df['血压'].values)):
df['最高血压'][i]=df['血压'][i][:3].replace('/','')
D:\python\lib\site-packages\ipykernel_launcher.py:2: SettingWithCopyWarning:
A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
brr=df.groupby(by='最高血压')['胰岛素含量'].mean()
brr
最高血压
100 19.056410
105 12.550000
110 10.926744
115 7.300000
120 14.712698
125 4.850000
127 10.900000
128 7.500000
129 6.400000
130 10.003200
135 9.825000
140 11.343182
141 9.700000
145 5.266667
150 14.278571
151 3.700000
155 13.700000
156 8.100000
159 7.000000
160 9.932609
170 8.575000
175 5.200000
180 9.164286
190 9.057143
200 7.642857
208 10.300000
210 18.500000
230 14.800000
80 8.200000
90 6.080000
95 11.500000
Name: 胰岛素含量, dtype: float64
#最高血压和胰岛素含量间的关系 无明显关系
plt.bar(brr.keys(),brr.values)
plt.title('Relationship between maximum blood pressure and insulin content')
plt.xlabel('maximum blood pressure')
plt.ylabel('insulin content')
Text(0, 0.5, 'insulin content')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cJ8bulQG-1627093577700)(%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_files/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_74_1.png)]
brr=df.groupby(by='尿糖值')['胰岛素含量'].mean()
brr
尿糖值
+- 11.324138
1+ 14.154348
2+ 13.060870
2+ 11 8.050000
3+ 15.146341
4+ 11.094132
Name: 胰岛素含量, dtype: float64
#尿糖值和胰岛素含量间的关系 无明显关系
plt.plot(brr.keys(),brr.values)
plt.title('Relationship between urinary sugar and insulin content')
plt.xlabel('urinary sugar')
plt.ylabel('insulin content')
Text(0, 0.5, 'insulin content')
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CgaGOMcx-1627093577700)(%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_files/%E6%95%B0%E6%8D%AE%E5%88%86%E6%9E%90_76_1.png)]
129 6.400000
130 10.003200
135 9.825000
140 11.343182
141 9.700000
145 5.266667
150 14.278571
151 3.700000
155 13.700000
156 8.100000
159 7.000000
160 9.932609
170 8.575000
175 5.200000
180 9.164286
190 9.057143
200 7.642857
208 10.300000
210 18.500000
230 14.800000
80 8.200000
90 6.080000
95 11.500000
Name: 胰岛素含量, dtype: float64
#最高血压和胰岛素含量间的关系 无明显关系
plt.bar(brr.keys(),brr.values)
plt.title('Relationship between maximum blood pressure and insulin content')
plt.xlabel('maximum blood pressure')
plt.ylabel('insulin content')
Text(0, 0.5, 'insulin content')
[外链图片转存中…(img-cJ8bulQG-1627093577700)]
brr=df.groupby(by='尿糖值')['胰岛素含量'].mean()
brr
尿糖值
+- 11.324138
1+ 14.154348
2+ 13.060870
2+ 11 8.050000
3+ 15.146341
4+ 11.094132
Name: 胰岛素含量, dtype: float64
#尿糖值和胰岛素含量间的关系 无明显关系
plt.plot(brr.keys(),brr.values)
plt.title('Relationship between urinary sugar and insulin content')
plt.xlabel('urinary sugar')
plt.ylabel('insulin content')
Text(0, 0.5, 'insulin content')
[外链图片转存中…(img-CgaGOMcx-1627093577700)]