Numpy & Pandas (莫烦 Python 数据处理教程)
Matplotlib Python 画图教程 (莫烦Python)
sudo pip3 install numpy/pandas
numpy
基于矩阵
array.ndim
array.shape
array.size
array.dtypes
创建数组
numpy.array([1,2,3], dtype=numpy.int/float)
numpy.array([ [1,2,3], [4,5,6] ])
二维
.zeros( (2,3) )
.ones
.empty
.arrange(10,20,2)
起始,终止,步长
.linspace(1,10,20)
从1到10分成20段
.reshape((3,4))
基础运算
+ - * /
逐个加减乘除
np.dot(a,b)
a.dot(b)
矩阵a和b相乘
np.sin()
调用函数
np.random.random((2,4))
np.sum(a, axis=0)
np.min(a, axis=0)
np.max(a)
矩阵a中每列、每行、所有
b < 3
b中元素用True和False显示比较结果
np.argmin(a)
索引
np.mean(a)
a.mean()
平均值
np.median(a)
中位数
np.cumsum(a)
累加
np.diff(a)
累差
np.nonezero(a)
np.sort(a)
np.transpose(a)
转置 a.T
np.clip(a,5,9)
小于5的都变成5,大于9的都变成9。滤波?
a[2]
a[2,1]
a[2][1]
a[2,:]
a[2,1:3]
数组合并、分割、复制
np.vstack((a,b))
上下合并
np.hstack((a,b))
左右合并
np.concatenate((a,b,b,a),axis=0)
多个合并,可设方向0上下1左右
np.split(a,2,axis=1)
纵向分割为2部分
np.array_split()
不等分割
np.vsplit()
np.hsplit()
b=a
浅copy,改变一个也会改变另外的
b=a.copy()
深copy,改变a不会改变b
pandas
有点像电子表格
基础操作
pd.Series([1,2,3,no.nan,44,1])
pd.date_range('20191001',periods=6)
pd.DataFrame(np.random.randn(6,4),index=dates,columns=['a','b','c','d'])
类似电子表格
pd.DataFrame({})
也可以用字典来定义
a.index
a.columns
a.values
a.sort_insex(axis=1,ascending=False)
按表头倒序排序
a.sort_values(by='c')
按c列数值排序
a.describe()
计数、平均值、最大值、最小值等
a.loc['标签']
筛选数据
a.loc[:,['标签1','标签2']]
a.iloc[3]
a.iloc[3,1]
a.iloc[3:5,1:3]
a.ix[:3,['标签']]
a[a.标签>8]
处理NaN数据
a.dropna(axis=0,how='any/all')
a.fillna(value=0)
a.isnull()
导入导出
pd.read_csv('文件名') _table _excel _pickle等
a.to_csv等
合并
pd.concat([a,b,c],axis=0)
ignore_index=True
join='outer/inner'
join_axes=[a.index]
a.append(b,ignore_index=True)
只能纵向
pd.merge(a,b,on='key')
按标签合并
how=[ 'inner','left', 'right', 'outer']
indicator=True
left_index=True, right_index=True
suffixes=['XX']
matplotlib
sudo apt-get install python3-matplotlib
sudo pip3 install matplotlib
import matplotlib.pyplot as plt
plt.plot(x,y,color='red',linewidth=1,linestyle='--')
plt.bar .scatter .box等
plt.show()
plt.figure(num=1,figsize=(8,5))
多个图片
plt.xlim((-1,2))
x轴取值范围
plt.ylim((-2,3))
plt.xlabel('x轴')
x轴名称
plt.ylabel('y轴')
plt.xticks(新的取值间隔)
plt.yticks([-2,-1,1.2,3],[r'$very\ good$','b','c','d'])
ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
ax.spines['bottom'].set_position(('data',0))
移动坐标轴
ax.spines['left'].set_position(('data',0))
plt.legend(handles=[ ],labels=[' '],loc='upper right')
图例
plt.annotate( )
标注
plt.text( )
注释
.set_bbox( )
透明度
plt.scatter( )
散点图
plt.bar( )
柱状图
plt.contour( )
等高线图
plt.imshow( )
随机矩阵画图
plt.colorbar( )
from mpl_toolkits.mplot3d import Axes3D
3D图像
plt.subplot(2,2,1)
子图。两行两列的第1个位置plt.subplot2grid((3,3),(0,0),colspan=3,rowspan=1)
import matplotlib.gridspec as gridspec
gridspec.GridSpec(3,3)
plt.subplot(gs[1, :2])
plt.subplots( )
left, bottom, width, height =
图中图
.twinx()
次坐标
from matplotlib import animation
动画