Pandas是Python中很是经常使用的数据处理工具,使用起来很是方便。它创建在NumPy数组结构之上,因此它的不少操做经过NumPy或者Pandas自带的扩展模块编写,这些模块用Cython编写并编译到C,而且在C上执行,所以也保证了处理速度。python
今天咱们就来体验一下它的强大之处。数组
使用pandas能够很方便地进行数据建立,如今让咱们建立一个5列1000行的pandas DataFrame:bash
mu1, sigma1 = 0, 0.1
mu2, sigma2 = 0.2, 0.2
n = 1000df = pd.DataFrame(
{
"a1": pd.np.random.normal(mu1, sigma1, n),
"a2": pd.np.random.normal(mu2, sigma2, n),
"a3": pd.np.random.randint(0, 5, n),
"y1": pd.np.logspace(0, 1, num=n),
"y2": pd.np.random.randint(0, 2, n),
}
)
复制代码
生成以下所示的数据:app
Pandas 绘图函数返回一个matplotlib的坐标轴(Axes),因此咱们能够在上面自定义绘制咱们所须要的内容。好比说画一条垂线和平行线。这将很是有利于咱们:dom
1.绘制平均线函数
2.标记重点的点工具
import matplotlib.pyplot as plt
ax = df.y1.plot()
ax.axhline(6, color="red", linestyle="--")
ax.axvline(775, color="red", linestyle="--")
plt.show()
复制代码
咱们还能够自定义一张图上显示多少个表:spa
fig, ax = plt.subplots(2, 2, figsize=(14,7))
df.plot(x="index", y="y1", ax=ax[0, 0])
df.plot.scatter(x="index", y="y2", ax=ax[0, 1])
df.plot.scatter(x="index", y="a3", ax=ax[1, 0])
df.plot(x="index", y="a1", ax=ax[1, 1])
plt.show()
复制代码
Pandas可以让咱们用很是简单的方式得到两个图形的形状对比:3d
df[["a1", "a2"]].plot(bins=30, kind="hist")
plt.show()
复制代码
还能容许多图绘制:code
df[["a1", "a2"]].plot(bins=30, kind="hist", subplots=True)
plt.show()
复制代码
固然,生成折线图也不在画下:
df[['a1', 'a2']].plot(by=df.y2, subplots=True)
plt.show()
复制代码
Pandas还能用于拟合,让咱们用pandas找出一条与下图最接近的直线:
最小二乘法计算和该直线最短距离:
df['ones'] = pd.np.ones(len(df))
m, c = pd.np.linalg.lstsq(df[['index', 'ones']], df['y1'], rcond=None)[0]
复制代码
根据最小二乘的结果绘制y和拟合出来的直线:
df['y'] = df['index'].apply(lambda x: x * m + c)
df[['y', 'y1']].plot()
plt.show()
复制代码
咱们的文章到此就结束啦,若是你但愿咱们今天的Python 教程,请持续关注咱们,若是对你有帮助,麻烦在下面点一个赞/在看哦
Python实用宝典 (pythondict.com)
不仅是一个宝典
欢迎关注公众号:Python实用宝典
原文来自Python实用宝典:Python pandas高效数据处理之绘图