📢 转载信息
原文链接:https://machinelearningmastery.com/7-pandas-tricks-to-handle-large-datasets/
原文作者:Iván Palomares Carrascosa
引言
在 Python 中处理大型数据集时,我们难免会遇到内存限制和处理工作流程缓慢的挑战。值得庆幸的是,功能多样且能力惊人的 Pandas 库提供了专门的工具和技术来应对大型(通常性质复杂且具有挑战性)数据集,包括表格数据、文本数据或时间序列数据。本文将介绍该库为有效管理此类大型数据集而提供的 7 个技巧。
1. 分块数据集加载
通过在 Pandas 的 read_csv()
函数中使用 chunksize
参数来读取包含在 CSV 文件中的数据集,我们可以将大型数据集以指定大小的更小、更易于管理的块进行加载和处理。这有助于防止出现内存溢出等问题。
import pandas as pd
def process(chunk):
"""Placeholder function that you may replace with your actual code for cleaning and processing each data chunk."""
print(f"Processing chunk of shape: {chunk.shape}")
chunk_iter = pd.read_csv("https://raw.githubusercontent.com/frictionlessdata/datasets/main/files/csv/10mb.csv", chunksize=100000)
for chunk in chunk_iter:
process(chunk)
2. 为内存效率优化进行数据类型下钻
当对大量数据元素应用微小的更改时,它们可以产生巨大的影响。使用如 astype()
这样的函数将数据类型转换为较低位表示法就是这种情况。这是一种简单但非常有效的方法,如下所示。
为了便于解释,本例中我们(不使用分块处理)将数据集加载到 Pandas 数据框中:
url = "https://raw.githubusercontent.com/frictionlessdata/datasets/main/files/csv/10mb.csv"
df = pd.read_csv(url)
df.info()
# Initial memory usage
print("Before optimization:", df.memory_usage(deep=True).sum() / 1e6, "MB")
# Downcasting the type of numeric columns
for col in df.select_dtypes(include=["int"]).columns:
df[col] = pd.to_numeric(df[col], downcast="integer")
for col in df.select_dtypes(include=["float"]).columns:
df[col] = pd.to_numeric(df[col], downcast="float")
# Converting object/string columns with few unique values to categorical
for col in df.select_dtypes(include=["object"]).columns:
if df[col].nunique() / len(df) < 0.5:
df[col] = df[col].astype("category")
print("After optimization:", df.memory_usage(deep=True).sum() / 1e6, "MB")
亲自尝试一下,您会注意到效率上的巨大差异。
3. 使用类别数据类型处理频繁出现的字符串
通过将字符串映射到整数标识符,将包含重复字符串的属性编码为类别数据类型,可以更有效地处理它们。例如,使用公开的可用的星座数据集,可以按如下方式将 12 个星座名称映射为类别类型:
import pandas as pd
url = 'https://raw.githubusercontent.com/plotly/datasets/refs/heads/master/horoscope_data.csv'
df = pd.read_csv(url)
# Convert 'sign' column to 'category' dtype
df['sign'] = df['sign'].astype('category')
print(df['sign'])
4. 以高效格式保存数据:Parquet
Parquet 是一种二进制列式数据集格式,与纯文本 CSV 相比,它可以实现更快的读写速度。因此,对于非常大的文件,它可能是值得考虑的首选选项。像前面介绍的星座数据集中重复的字符串在内部也会被压缩,以进一步简化内存使用。请注意,在 Pandas 中读写 Parquet 需要安装可选的引擎,例如 pyarrow
或 fastparquet
。
# Saving dataset as Parquet
df.to_parquet("horoscope.parquet", index=False)
# Reloading Parquet file efficiently
df_parquet = pd.read_parquet("horoscope.parquet")
print("Parquet shape:", df_parquet.shape)
print(df_parquet.head())
5. GroupBy 聚合
大型数据集分析通常涉及获取统计数据来汇总分类列。先前将重复字符串转换为类别列(技巧 3)在分组数据(例如按类别分组)等过程中具有后续优势,如下所示,我们按星座对星座实例进行聚合:
numeric_cols = df.select_dtypes(include=['float', 'int']).columns.tolist()
# Perform groupby aggregation safely
if numeric_cols:
agg_result = df.groupby('sign')[numeric_cols].mean()
print(agg_result.head(12))
else:
print("No numeric columns available for aggregation.")
请注意,所使用的聚合方法——算术平均值——仅影响数据集中纯数字的特征:在本例中,是每个星座中的幸运数字。对这些幸运数字求平均可能意义不大,但此示例仅为说明如何更高效地处理大型数据集。
6. 使用 query() 和 eval() 进行高效过滤和计算
为了说明使用上述函数如何在规模化处理时使过滤和其他计算更快,我们将向我们的星座数据集中添加一个新的、合成的数值特征。query()
函数用于根据条件过滤行,而 eval()
函数应用于计算,通常涉及多个数值特征。这两个函数都旨在高效处理大型数据集:
df['lucky_number_squared'] = df['lucky_number'] ** 2
print(df.head())
numeric_cols = df.select_dtypes(include=['float', 'int']).columns.tolist()
if len(numeric_cols) >= 2:
col1, col2 = numeric_cols[:2]
df_filtered = df.query(f"{col1} > 0 and {col2} > 0")
df_filtered = df_filtered.assign(Computed=df_filtered.eval(f"{col1} + {col2}"))
print(df_filtered[['sign', col1, col2, 'Computed']].head())
else:
print("Not enough numeric columns for demo.")
7. 向量化字符串操作,实现高效的列转换
在 Pandas 数据集上执行向量化字符串操作是一个无缝且几乎透明的过程,比手动替代方法(如循环)效率更高。此示例展示了如何对星座数据集中的文本数据应用简单的处理:
# We set all zodiac sign names to uppercase using a vectorized string operation
df['sign_upper'] = df['sign'].str.upper()
# Example: counting the number of letters in each sign name
df['sign_length'] = df['sign'].str.len()
print(df[['sign', 'sign_upper', 'sign_length']].head(12))
总结
本文介绍了在使用 Pandas 库来更有效地管理大型数据集时,通常被忽略但简单有效的 7 个技巧,涵盖了从数据加载到处理和优化存储的整个过程。尽管最近出现了一些专注于大型数据集高性能计算的新库,但对于许多用户来说,坚持使用像 Pandas 这样成熟的库可能仍然是一种平衡且更受欢迎的方法。
🚀 想要体验更好更全面的AI调用?
欢迎使用青云聚合API,约为官网价格的十分之一,支持300+全球最新模型,以及全球各种生图生视频模型,无需翻墙高速稳定,文档丰富,小白也可以简单操作。
评论区