在 Pandas 中,可以使用 apply 函数将函数应用于 DataFrame 中的某一列。然而,要多线程地应用函数,可以使用 concurrent.futures 模块中的 ThreadPoolExecutor 类来实现。

以下展示了多线程应用函数于 DataFrame 列的步骤:

  1. 导入 concurrent.futures 模块:
import concurrent.futures
  1. 定义一个函数,该函数将在多线程中应用于 DataFrame 的某一列:
def my_func(x):
    return x * 2    # 例如,将列中的每个元素乘以 2
  1. 创建 ThreadPoolExecutor 对象,并调用它的 map 方法来应用函数:
# 假设 df 是一个 DataFrame,col 是需要应用函数的列名
with concurrent.futures.ThreadPoolExecutor() as executor:
    results = executor.map(my_func, df[col])
  1. 将结果更新到原始 DataFrame 中:
df[col] = list(results)

以下是一个完整的代码示例:

import pandas as pd
import concurrent.futures

# 定义函数
def my_func(x):
    return x * 2

# 创建 DataFrame
data = {'a': [1, 2, 3], 'b': [4, 5, 6]}
df = pd.DataFrame(data)

# 应用函数并更新结果
col = 'b'
with concurrent.futures.ThreadPoolExecutor() as executor:
    results = executor.map(my_func, df[col])

df[col] = list(results)

print(df)

输出:

   a   b
0  1   8
1  2  10
2  3  12

通过使用多线程,可以显著提高对 DataFrame 列进行函数应用的效率,特别是在处理大型数据集时。

Pandas 多线程应用函数至 DataFrame 列

原文地址: https://www.cveoy.top/t/topic/og5t 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录