美文网首页呆鸟的Python数据分析呆鸟译Py
重磅消息:Pandas 2.x 即将来袭

重磅消息:Pandas 2.x 即将来袭

作者: 呆鸟的简书 | 来源:发表于2023-02-26 16:50 被阅读0次
    Pandas 2.x

    呆鸟说:根据 Pandas 开发团队发布的消息,3月以后,Pandas 就要进入 2.x 时代了,Python 数据分析师快来入坑吧!

    具体链接如下:https://pandas.pydata.org/docs/dev/whatsnew/index.html

    Release Note

    主要改进

    1. 可配置选项,mode.dtype_backend 返回 pyarrow 数据类型
    2. 使用 pip 安装可选的支持库
    3. Index 支持 Numpy 的 numeric 数据类型
    4. 使用 Copy_on_write(写入时复制)机制,提高写入性能
    Python大咖谈

    具体说明如下:

    一、加入 pyarrow 数据类型

    加入对 Apache Arrow 的支持,是 Pandas 2.x 最大的变化。首先介绍一下什么是 Arrow。

    Arrow 是 Apache 软件基金会支持的内存分析开发平台,它可以快速处理和移动大规模数据,为数据的扁平化和分层制定了标准化的,与语言无关的列式内存格式,以便在硬件层面上进行更高效的数据分析操作。

    pyarrow 是为 Python 社区提供的 Arrow 支持库,与 NumPy 和 Pandas 的集成度非常高,从 2.0 版开始,Pandas 专门加入了对 pyarrow 数据类型的支持。

    使用 pyarrow,可以让 pandas 处理数据的数据操作更快,内存使用效率更高,尤其是在处理超大数据集时,其优势更明显。

    以下内容是 Pandas 2.0 开发公告介绍的对 arrow 的支持说明。

    Pandas 之前在 read_csv()read_excel()read_json()read_sql()to_numeric() 等函数中使用 use_nullable_dtypes 关键字参数,让这些函数可以自动转换 nullable 数据类型,为了简化操作,Pandas 新增了一个 nullable_dtypes 选项,允许在没有明确指定时,把关键字参数在全局范围内设为 True。启用该选项的方式如下:

    pd.options.mode.nullable_dtypes = True
    

    这个选项仅用于函数的 use_nullable_dtypes 关键字。

    Pandas 又新增了一个全局配置项: mode.dtype_backend,用于连接上述 read_csv() 等函数中的 use_nullable_dtypes=True 参数,以选择 nullable 数据类型。

    DataFrame.convert_dtypes()Series.convert_dtypes() 两种方法也可以使用
    mode.dtype_backend 选项。

    mode.dtype_backend 的默认值为 pandas,返回的是 Numpy 支持的 nullable 数据类型。但现在也可以设置为 pyarrow,返回 pyarrow 支持的 nullable 数据类型,即 ArrowDtype

    示例代码如下:

    In [13]: import io
    
    In [14]: data = io.StringIO("""a,b,c,d,e,f,g,h,i
       ....:     1,2.5,True,a,,,,,
       ....:     3,4.5,False,b,6,7.5,True,a,
       ....: """)
       ....: 
    
    In [15]: with pd.option_context("mode.dtype_backend", "pandas"):
       ....:     df = pd.read_csv(data, use_nullable_dtypes=True)
       ....: 
    
    In [16]: df.dtypes
    Out[16]: 
    a             Int64
    b           Float64
    c           boolean
    d    string[python]
    e             Int64
    f           Float64
    g           boolean
    h    string[python]
    i             Int64
    dtype: object
    
    In [17]: data.seek(0)
    Out[17]: 0
    
    # 主要看下面这行代码
    In [18]: with pd.option_context("mode.dtype_backend", "pyarrow"):
       ....:     df_pyarrow = pd.read_csv(data, use_nullable_dtypes=True, engine="pyarrow")
       ....: 
    
    In [19]: df_pyarrow.dtypes
    Out[19]: 
    a     int64[pyarrow]
    b    double[pyarrow]
    c      bool[pyarrow]
    d    string[pyarrow]
    e     int64[pyarrow]
    f    double[pyarrow]
    g      bool[pyarrow]
    h    string[pyarrow]
    i      null[pyarrow]
    dtype: object
    

    二、使用 pip 安装可选的支持库

    使用 pip 安装 pandas 时,可以指定要安装的可选支持库。

    pip install "pandas[performance, aws]>=2.0.0"
    

    三、Index 支持 Numpy 的 numeric 数据类型

    Pandas 2.0 开始,可以在 Index 中使用 numpy 的数字型数据类型。Pandas 之前只能用 int64uint64float64 等数据类型,从 2.0 开始,Pandas 支持所有 numpy 的 numeric 数据,如 int8int16int32int64uint8uint16uint32uint64float32float64 等。

    示例代码如下:

    In [1]: pd.Index([1, 2, 3], dtype=np.int8)
    Out[1]: Index([1, 2, 3], dtype='int8')
    
    In [2]: pd.Index([1, 2, 3], dtype=np.uint16)
    Out[2]: Index([1, 2, 3], dtype='uint16')
    
    In [3]: pd.Index([1, 2, 3], dtype=np.float32)
    Out[3]: Index([1.0, 2.0, 3.0], dtype='float32')
    

    四、提高写入性能

    • 为以下方法新增了惰性复制机制,推迟复制,直到修改相关对象时才真正复制。启用 Copy-on-Write 机制之后,以下方法仅返回视图,这比常规的性能有了显著提升。

    (以下仅为部分支持该机制的方法,详见文档)
    * DataFrame.reset_index() / Series.reset_index()
    * DataFrame.set_index()
    * DataFrame.reindex() / Series.reindex()
    * DataFrame.reindex_like() / Series.reindex_like()
    * DataFrame.drop()
    * DataFrame.dropna() / Series.dropna()
    * DataFrame.select_dtypes()
    * DataFrame.align() / Series.align()
    * Series.to_frame()
    * DataFrame.rename() / Series.rename()
    * DataFrame.add_prefix() / Series.add_prefix()
    * DataFrame.add_suffix() / Series.add_suffix()
    * DataFrame.drop_duplicates() / Series.drop_duplicates()
    * DataFrame.filter() / Series.filter()
    * DataFrame.head() / Series.head()
    * DataFrame.tail() / Series.tail()
    * DataFrame.pop() / Series.pop()
    * DataFrame.replace() / Series.replace()
    * DataFrame.shift() / Series.shift()
    * DataFrame.sort_index() / Series.sort_index()
    * DataFrame.sort_values() / Series.sort_values()
    * DataFrame.truncate()
    * DataFrame.iterrows()
    * DataFrame.fillna() / Series.fillna()
    * DataFrame.where() / Series.where()
    * DataFrame.astype() / Series.astype()
    * concat()

    • 以 Series 的形式处理 DataFrame 的单个列(例如,df["col"])时,每次构建都返回一个新对象,启用 Copy-on-Write 时,不再多次返回相同的 Series 对象。
    • 使用已有的 Series 构建 Series,且默认选项为 copy=False 时,Series 构造函数将使用惰性复制机制,即推迟复制,直到发生数据修改时才真正复制。
    • 使用已有的 DataFrame 构建 DataFrame,且默认选项为 copy=False 时,DataFrame 构造函数也使用惰性复制机制。
    • 使用 Series 字典构建 DataFrame,且默认选项为 copy=False 时,也使用惰性复制机制。
    • 启用 Copy-on-Write 时,使用链式赋值设置值(例如,df["a"][1:3] = 0)将引发异常。在此模式下,链式赋值不能正常运行。
    • DataFrame.replace()inplace=True 时,使用 Copy-on-Write
    • DataFrame.transpose() 使用 Copy-on-Write 机制。
    • 算术运算,如, ser *= 2 也支持 Copy-on-Write
      启用本选项的方式如下:
    # 方式一
    pd.set_option("mode.copy_on_write", True)
    
    # 方式二
    pd.options.mode.copy_on_write = True
    
    # 局部启用的方式
    with pd.option_context("mode.copy_on_write", True):
        ...
    

    推荐书单

    《Pandas1.x实例精解》详细阐述了与Pandas相关的基本解决方案,主要包括Pandas基础,DataFrame基本操作,创建和保留DataFrame,开始数据分析,探索性数据分析,选择数据子集,过滤行,对齐索引,分组以进行聚合、过滤和转换,将数据重组为规整形式,组合Pandas对象,时间序列分析,使用Matplotlib、Pandas和Seaborn进行可视化,调试和测试等内容。此外,该书还提供了相应的示例、代码,以帮助读者进一步理解相关方案的实现过程。

    Pandas1.x实例精解

    相关文章

      网友评论

        本文标题:重磅消息:Pandas 2.x 即将来袭

        本文链接:https://www.haomeiwen.com/subject/yxdcldtx.html