Pandas 多线程应用函数于 DataFrame 列:性能优化指南
在 Pandas 中,使用 apply 函数可以将函数应用于 DataFrame 的某一列。为了在多线程中执行此操作,可以使用 concurrent.futures 模块中的 ThreadPoolExecutor。以下是一个示例代码:
import pandas as pd
import concurrent.futures
# 定义一个函数,将值加倍
def double_value(x):
return x * 2
# 创建一个 DataFrame
df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]})
# 定义一个 ThreadPoolExecutor,使用 4 个线程
executor = concurrent.futures.ThreadPoolExecutor(max_workers=4)
# 使用 submit 方法将函数应用于 DataFrame 的某一列
# 注意,这里传递的是函数名,而不是函数调用
futures = [executor.submit(double_value, x) for x in df['B']]
# 等待所有任务完成
concurrent.futures.wait(futures)
# 将结果存储回 DataFrame
df['B'] = [f.result() for f in futures]
print(df)
输出:
A B
0 1 8
1 2 10
2 3 12
在上面的示例中,我们使用了 ThreadPoolExecutor 来并行地将 double_value 函数应用于 df['B'] 列中的每个元素。每个元素都会被提交给线程池中的一个线程,然后我们等待所有任务完成,并将结果存储回 DataFrame 中。
注意:
- 确保您要应用的函数是线程安全的,这意味着它可以同时在多个线程中执行而不会导致数据损坏。
- 如果您的函数需要访问共享资源,请使用适当的同步机制(例如锁)来防止竞争条件。
通过这种方式,您可以使用多线程来加速 Pandas DataFrame 的列处理,提高数据处理效率。
原文地址: https://www.cveoy.top/t/topic/og42 著作权归作者所有。请勿转载和采集!