Python Seaborn&Pandas库简单上手

简介

Seaborn 是基于 Python 且非常受欢迎的图形可视化库,它是对Matplotlib的更高级的封装,使得作图更加方便快捷

基本操作

导入

python 复制代码
import seaborn as sns
import matplotlib.pyplot as plt

以下对seabornmatplotlib的引用均别名均使用snsplt

内置数据集(Seaborn)

Seaborn内置了一些数据集用于示例,使用sns.get_dataset_names()进行获取
所有可调用的内置数据集也可以在Github仓库内找到

数据集的加载和预览(Pandas)

使用dft = sns.load_dataset('数据集名')加载数据集,此函数的签名如下

plaintext 复制代码
    Load an example dataset from the online repository (requires internet).

    This function provides quick access to a small number of example datasets
    that are useful for documenting seaborn or generating reproducible examples
    for bug reports. It is not necessary for normal usage.

    Note that some of the datasets have a small amount of preprocessing applied
    to define a proper ordering for categorical variables.

    Use :func:`get_dataset_names` to see a list of available datasets.

    Parameters
    ----------
    name : str
        Name of the dataset (``{name}.csv`` on
        https://github.com/mwaskom/seaborn-data).
    cache : boolean, optional
        If True, try to load from the local cache first, and save to the cache
        if a download is required.
    data_home : string, optional
        The directory in which to cache data; see :func:`get_data_home`.
    kws : keys and values, optional
        Additional keyword arguments are passed to passed through to
        :func:`pandas.read_csv`.

    Returns
    -------
    df : :class:`pandas.DataFrame`
        Tabular data, possibly with some preprocessing applied.

它返回一个Pandas的DataFrame对象,我们将其赋予dft

  • dft.head():可以预览数据框头部的数据,默认为5条,可以通过传入形参n修改,类似地,使用dft.tail可以预览尾部的数据
  • dft.info():可以获得数据框的所有信息,可以使用print将其打印出来
  • dft.shape()dft.size():可以分别获得数据框的长宽信息和总元素个数
  • dft.plot():Pandas绘图方法,获得简单的折线图
  • dft.describe():获得各个列的“描述”(如总数、均值、标准差、X分位数、最小、最大等)

索引和切片(Pandas)

我们以安斯库姆四重奏数据集anscombedataset列为例

python 复制代码
dfa = sns.load_dataset('anscombe')

使用Pandas索引数据框行/列的方式有两种dfa.locdfa.iloc

  • dfa.loc[行标签, 列标签(没有可以省略)]:基于标签,切片时支持推导式
    • 若我们想获取dataset列,可以使用dfa.loc[:,'dataset]
    • 若我们想获取所有datasetI的行,可以使用dfa.loc[dfa['dataset'] == 'I']
    • 支持整数标签,但范围遵循左闭右闭,若我们想获取所有标签2-4的行,可以使用df.loc[2:4]
  • dfa.iloc[行索引, 列索引(没有可以省略)]:基于索引(这里的i指的是index),切片时支持推导式,索引从0开始,左闭右开
    • 若我们想获取列索引0到2的数据,可以使用dfa.iloc[:, 0:3]
    • 若我们想获取行索引0到2的数据,可以使用dfa.iloc[0:3]

类似的,Pandas索引单个元素的方式也有两种dfa.atdfa.iat

  • dfa.at[行标签, 列标签],整数标签时左闭右闭
  • dfa.iat[行索引, 列索引]左闭右开

当然也可以连着使用loc/ilocat/iat,比如dfa.loc[:, '某个列'].iat[1],这将获得某个列中索引为1的元素

列操作(Pandas)

暂时只有unique()

我们以安斯库姆四重奏数据集anscombedataset列为例

python 复制代码
dfa = sns.load_dataset('anscombe')

引用其dataset列,我们将获得一个Pands的Series序列对象

  • dfa.dataset.unique():去重,返回一个NumPy数组,里面包含该列去重后不重复数据

数据清洗(Pandas)

首先查看一个数据框中是否有NaN的数据

  • dfa.is_na():返回一个与原数据框形状形同的布尔数据框,其中为NaN的数据为True,其余为False,可以使用dfa.is_na().sum()(默认参数axis=0)获取每一中NaN数据的总和数
  • dfa[dfa.isna().any(axis=1)]:获取dfa中存在NaN数据的行(在Pandas中,直接选取数据框时遵循列优先,列的axis为0而行的axis为1,这与NumPy中数组的索引是相反的,因此使用dfa['xxx']获取的是xxx列的数据,但需要与切片区分,入dfa[252:256]选择的是第253-256行数据)。或使用NaN_rows = dfa[dfa.isna().any(axis=1)]dfa.loc[NaN_rows.index]获取dfa中NaN的数据行,在删除后如果需要重新排布行标签(如果是数字的话,行索引),则需要使用dfa.reset_index(drop=True)(设置drop=True时,原来的索引会被删去)

对于数据的清洗

  • dfa.fillna(dict):传入一个Scalar或dict[str, Series],用于将字典中为键的列中的NaN的数据补全为字典中的值,比如dfa['xxx'].mean()则补全为该列的平均数
  • dfa.dropna():返回一个新的DataFrame,将含NaN数据的条目删去

绘图(Seaborn)

暂时只有scatterplot

我们以tips数据集为例

python 复制代码
ds = sns.load_dataset("tips")
  • sns.scatterplot(参数):绘制离散图
    • 参数data:绘图的数据集,传入Pandas DataFrame对象
    • 参数x:x坐标,填写Pandas数据框列标签
    • 参数y:y坐标,填写Pandas数据框列标签
游客

全部评论 (0)

暂无评论,快来抢沙发吧~