2

Pandas 2.0 中的新亮点

 1 year ago
source link: https://xugaoxiang.com/2023/03/22/pandas-2-features/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Pandas 是一个开源数据分析工具,广泛用于数据清洗、数据处理、数据分析等领域。相信经常做数据处理的童鞋比较熟悉。随着现在数据量越来越多,pandas 的局限性也日渐凸显,在处理大数据时非常恼火,从而选择更加合适的工具,如 pyspark 等大数据处理框架。Pandas 2.0 是 Pandas 库的最新版本,它带来了一些重要的改进和新功能。我们来看看进化之后的新功能。

原生时区支持

Pandas 2.0 引入了原生时区支持,使得 Pandas 能够更好地处理时间序列数据。现在,Pandas 可以轻松地转换时区,并对时区信息进行计算。

import pandas as pd
import numpy as np

# 创建一个带有时区信息的时间戳系列
ts = pd.Series(pd.date_range('2022-01-01 00:00:00', periods=3, freq='H', tz='Europe/London'))

# 将时区转换为另一个时区
ts_utc = ts.dt.tz_convert('UTC')

# 显示原始和转换后的时间戳
print(ts)
print(ts_utc)
0   2022-01-01 00:00:00+00:00
1   2022-01-01 01:00:00+00:00
2   2022-01-01 02:00:00+00:00
dtype: datetime64[ns, Europe/London]
0   2022-01-01 00:00:00+00:00
1   2022-01-01 01:00:00+00:00
2   2022-01-01 02:00:00+00:00
dtype: datetime64[ns, UTC]

类型化的列

Pandas 2.0 引入了类型化的列,使得用户可以更好地管理数据类型,并提高数据处理的效率。现在,用户可以在创建数据帧时指定每个列的数据类型,这使得数据帧的类型更加清晰明了。

import pandas as pd
import numpy as np

# 创建一个带有类型化列的数据帧
df = pd.DataFrame({
    'A': pd.Series(np.random.randn(5), dtype='float32'),
    'B': pd.Series(np.random.randint(0, 10, 5), dtype='int32'),
    'C': pd.Series(np.random.choice(['foo', 'bar', 'baz'], 5), dtype='category')
})

# 显示列的数据类型
print(df.dtypes)
A           float32
B             int32
C          category
dtype: object

Datetime 类型的可空性

Pandas 2.0 引入了 Datetime 类型的可空性,使得用户可以更好地处理缺失值。现在,Pandas 可以轻松地处理缺失值日期时间,而不需要额外的处理。

import pandas as pd
import numpy as np

# 创建一个带有空值日期时间的序列
dt = pd.Series([pd.Timestamp('2022-01-01'), pd.NaT, pd.Timestamp('2022-01-03')])

# 显示带有空值的序列
print(dt)
0   2022-01-01
1          NaT
2   2022-01-03
dtype: datetime64[ns]

改进的分组操作

Pandas 2.0 引入了改进的分组操作,使得用户可以更加轻松地对数据进行分组和聚合。现在,用户可以轻松地在一个数据帧中同时进行多个分组操作,这大大提高了数据处理的效率。

import pandas as pd
import numpy as np

# 创建一个带有多个列的数据帧
df = pd.DataFrame({
    'A': ['foo', 'bar', 'foo', 'bar', 'foo', 'bar', 'foo', 'foo'],
    'B': ['one', 'one', 'two', 'three', 'two', 'two', 'one', 'three'],
    'C': np.random.randn(8),
    'D': np.random.randn(8)
})

# 按 A 和 B 列分组,并对 C 列应用 mean 函数
grouped = df.groupby(['A', 'B']).mean()

# 显示分组后的数据
print(grouped)
                  C         D
A   B                        
bar one    1.224593  1.277185
    three -0.672583  0

改进的IO性能

Pandas 2.0 引入了改进的 IO 性能,使得用户可以更加快速地读取和写入数据。现在,Pandas 可以更好地处理大型数据集,并提供更好的内存管理和压缩算法。

更好的内存管理

Pandas 2.0 引入了更好的内存管理,使得用户可以更加轻松地处理大型数据集。现在,Pandas 可以更好地管理内存,减少内存泄漏和内存碎片化问题。

Pandas 2.0 带来了许多重要的改进和新功能,使得 Pandas 更加强大和灵活。如果你是一个数据分析师或者数据科学家,那么 Pandas 2.0 绝对值得一试!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK