Py学习  »  Python

【Python】重磅新闻:Pandas 2.x 即将来袭

机器学习初学者 • 1 年前 • 179 次点击  

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


主要改进





  1. 可配置选项,mode.dtype_backend 返回 pyarrow 数据类型

  2. 使用 pip 安装可选的支持库

  3. Index 支持 Numpy 的 numeric 数据类型

  4. 使用 Copy_on_write(写入时复制)机制,提高写入性能

具体说明如下:


加入 pyarrow 数据类型




Pandas 2.x 最大的变化是加入了对 Apache Arrow 的支持。首先介绍一下什么是 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([123], dtype=np.int8)
Out[1]: Index([123], dtype='int8')

In [2]: pd.Index([12 3], dtype=np.uint16)
Out[2]: Index([123], dtype='uint16')

In [3]: pd.Index([123], dtype=np.float32)
Out[3]: Index([1.02.03.0], dtype='float32')



提高写入性能





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


        • DataFrame.reset_index() / Series.reset_index()

        • DataFrame.set_index()

        • DataFrame.set_axis() / Series.set_axis()

        • DataFrame.set_flags() / Series.set_flags()

        • DataFrame.rename_axis() / Series.rename_axis()

        • DataFrame.reindex() / Series.reindex()

        • DataFrame.reindex_like() / Series.reindex_like()

        • DataFrame.assign()

        • 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.droplevel() / Series.droplevel()

        • DataFrame.reorder_levels() / Series.reorder_levels()

        • DataFrame.between_time() / Series.between_time()

        • DataFrame.filter() / Series.filter()

        • DataFrame.head() / Series.head()

        • DataFrame.tail() / Series.tail()

        • DataFrame.isetitem()

        • DataFrame.pipe() / Series.pipe()

        • 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.squeeze() / Series.squeeze()

        • DataFrame.swapaxes()

        • DataFrame.swaplevel() / Series.swaplevel()

        • DataFrame.take() / Series.take()

        • DataFrame.to_timestamp() / Series.to_timestamp()

        • DataFrame.to_period() / Series.to_period()

        • DataFrame.truncate()

        • DataFrame.iterrows()

        • DataFrame.tz_convert() / Series.tz_localize()

        • DataFrame.fillna() / Series.fillna()

        • DataFrame.interpolate() / Series.interpolate()

        • DataFrame.ffill() / Series.ffill()

        • DataFrame.bfill() / Series.bfill()

        • DataFrame.where() / Series.where()

        • DataFrame.infer_objects() / Series.infer_objects()

        • DataFrame.astype() / Series.astype()

        • DataFrame.convert_dtypes() / Series.convert_dtypes()

        • 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):
    ...


往期精彩回顾




Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/152560
 
179 次点击