欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 美食 > Python数据分析及可视化中常用的6个库及函数(一)

Python数据分析及可视化中常用的6个库及函数(一)

2025/6/6 7:05:09 来源:https://blog.csdn.net/gsjthxy/article/details/148410256  浏览:    关键词:Python数据分析及可视化中常用的6个库及函数(一)

Python数据分析及可视化中常用的6个库及函数(一)

       摘要:下面列出 Python 进行数据分析与可视化时最常用的 6 个库,以及每个库中若干常用函数(方法)的功能、用法和示例。


1. NumPy

NumPy 是科学计算的基础库,提供高效的多维数组对象和大量数学函数。

  • numpy.array(object, dtype=None)
    功能:创建 ndarray。
    用法:np.array([1,2,3]),可指定类型。
    示例:

    import numpy as np
    a = np.array([1, 2, 3], dtype=float)
    # a -> array([1., 2., 3.])
    
  • numpy.arange([start,] stop[, step,][, dtype])
    功能:生成等差数列数组。
    用法:np.arange(0, 1, 0.2)
    示例:

    x = np.arange(0, 1, 0.2)
    # x -> array([0. , 0.2, 0.4, 0.6, 0.8])
    
  • numpy.linspace(start, stop, num=50[, endpoint, retstep, dtype])
    功能:生成指定个数的等间距数组。
    用法:np.linspace(0, π, 100)
    示例:

    x = np.linspace(0, np.pi, 5)
    # x -> array([0.        , 0.78539816, 1.57079633, 2.35619449, 3.14159265])
    
  • ndarray.reshape(shape)
    功能:改变数组形状,不拷贝数据。
    用法:a.reshape((2,3))
    示例:

    a = np.arange(6)
    b = a.reshape((2,3))
    # b -> array([[0,1,2],
    #             [3,4,5]])
    
  • numpy.mean(a, axis=None) / numpy.std(a, axis=None)
    功能:求均值/标准差,可沿指定轴。
    示例:

    data = np.random.randn(100, 3)
    m = np.mean(data, axis=0)   # 每列的均值
    s = np.std(data, axis=1)    # 每行的标准差
    

2. Pandas

Pandas 提供高性能的 DataFrame 和 Series,用于表格数据的读取、加工、查询与统计。

  • pandas.read_csv(filepath, **kwargs)
    功能:读取 CSV,返回 DataFrame
    示例:

    import pandas as pd
    df = pd.read_csv("data.csv", index_col=0)
    
  • DataFrame.head(n=5) / DataFrame.tail(n=5)
    功能:查看前/后 n 行。
    示例:

    df.head(3)
    df.tail(2)
    
  • DataFrame.describe()
    功能:生成数值列的统计汇总(计数、均值、分位数等)。
    示例:

    df.describe()
    
  • DataFrame.groupby(by)[aggfunc]
    功能:分组聚合。
    示例:

    grp = df.groupby("category")["value"].mean()
    
  • pandas.merge(left, right, on, how)
    功能:类似 SQL 的表连接。
    示例:

    df2 = pd.merge(df1, df_ref, on="id", how="left")
    
  • DataFrame.plot(kind, **kwargs)
    功能:调用 Matplotlib 画图。
    示例:

    df["value"].plot(kind="hist", bins=20, color="skyblue")
    

3. Matplotlib

最经典的绘图库,适合细粒度定制各种图表。

  • pyplot.figure(figsize=(w,h))
    功能:新建画布/窗口,指定大小。
    示例:

    import matplotlib.pyplot as plt
    plt.figure(figsize=(6,4))
    
  • pyplot.plot(x, y, fmt, **kwargs)
    功能:绘制折线/散点(通过 fmt 控制)。
    示例:

    x = np.linspace(0, 2*np.pi, 100)
    y = np.sin(x)
    plt.plot(x, y, 'r--', label="sin(x)")
    
  • pyplot.scatter(x, y, c, s)
    功能:绘制散点图,可指定颜色和大小。
    示例:

    plt.scatter(df.x, df.y, c=df.category, s=50, cmap="viridis")
    
  • pyplot.hist(x, bins, density)
    功能:绘制直方图。
    示例:

    plt.hist(data, bins=30, density=True, alpha=0.7)
    
  • pyplot.xlabel()/ylabel()/title()/legend()
    功能:添加坐标轴标签、标题、图例。
    示例:

    plt.xlabel("Time (s)")
    plt.ylabel("Amplitude")
    plt.title("Signal")
    plt.legend()
    

4. Seaborn

基于 Matplotlib,提供更高级的统计图表和默认美化样式。

  • seaborn.histplot(data, x, bins)
    功能:直方图/核密度图。
    示例:

    import seaborn as sns
    sns.histplot(df["value"], bins=20, kde=True, color="steelblue")
    
  • seaborn.boxplot(x, y, data)
    功能:箱线图,用于分组比较分布。
    示例:

    sns.boxplot(x="category", y="value", data=df)
    
  • seaborn.heatmap(data, annot)
    功能:热力图,常用于相关矩阵。
    示例:

    corr = df.corr()
    sns.heatmap(corr, annot=True, cmap="coolwarm")
    
  • seaborn.pairplot(data, hue)
    功能:变量两两散点矩阵与分布图。
    示例:

    sns.pairplot(df, hue="category")
    
  • seaborn.barplot(x, y, data, ci)
    功能:带置信区间的柱状图。
    示例:

    sns.barplot(x="group", y="score", data=df, ci=95)
    

5. SciPy

在 NumPy 基础上提供统计、优化、积分、信号处理等功能。

  • scipy.stats.ttest_ind(a, b)
    功能:独立样本 t 检验。
    示例:

    from scipy import stats
    t, p = stats.ttest_ind(group1, group2)
    
  • scipy.stats.pearsonr(x, y)
    功能:计算 Pearson 相关系数及 p 值。
    示例:

    r, p = stats.pearsonr(df.x, df.y)
    
  • scipy.optimize.curve_fit(func, xdata, ydata)
    功能:最小二乘拟合任意函数。
    示例:

    def model(x, a, b): return a*np.exp(b*x)
    popt, pcov = optimize.curve_fit(model, x, y)
    
  • scipy.integrate.quad(func, a, b)
    功能:一维数值积分。
    示例:

    area, err = integrate.quad(lambda t: np.sin(t), 0, np.pi)
    
  • scipy.cluster.hierarchy.dendrogram(linkage_matrix)
    功能:绘制层次聚类树状图。
    示例:

    from scipy.cluster import hierarchy
    Z = hierarchy.linkage(X, method='ward')
    hierarchy.dendrogram(Z)
    

6. Plotly (Plotly Express)

交互式可视化库,生成 HTML/JS 图表,可缩放、悬浮提示。

  • plotly.express.scatter(df, x, y, color)
    功能:交互式散点图。
    示例:

    import plotly.express as px
    fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
    fig.show()
    
  • plotly.express.line(df, x, y, title)
    功能:折线图。
    示例:

    fig = px.line(df_time, x="time", y="value", title="Time Series")
    fig.show()
    
  • plotly.express.bar(df, x, y, barmode)
    功能:柱状图/分组柱状图。
    示例:

    fig = px.bar(df, x="category", y="count", color="type", barmode="group")
    fig.show()
    
  • plotly.express.histogram(df, x, nbins)
    功能:直方图,支持分组。
    示例:

    fig = px.histogram(df, x="value", nbins=30, color="group")
    fig.show()
    
  • plotly.express.heatmap(data_frame, x, y, z)
    功能:热力图。
    示例:

    fig = px.density_heatmap(df, x="x", y="y", z="value")
    fig.show()
    

       以上 6 个库及其常用函数,几乎覆盖了从数据读取、清洗、统计分析到静态/交互式可视化的全流程。根据需求,可灵活组合使用。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词