python - 使用 pyarrow 在工作人员之间共享对象

标签 python pandas python-multiprocessing pyarrow

我想向由 multiprocessing.Pool.map() 创建的多个工作进程授予对共享 DataFrame 的只读访问权限。

我想避免复制和酸洗。

我知道 pyarrow 可以用于此目的。然而,我发现他们的文档相当麻烦。谁能提供一个例子来说明如何做到这一点?

最佳答案

https://github.com/apache/arrow/blob/master/python/examples/plasma/sorting/sort_df.py 处的示例是一个使用 Python 多处理在多个工作人员之间共享 Pandas 数据帧的工作示例(请注意,它需要您构建一个小型 Cython 库才能运行它)。

数据框通过 Arrow's Plasma object store 共享.

如果您不依赖于 Python 多处理,则可以使用 Ray用更简单的语法做你想做的事。

要授予多个工作人员对 Pandas 数据帧的只读访问权限,您可以执行以下操作。

import numpy as np
import pandas
import ray

ray.init()

df = pandas.DataFrame(np.random.normal(size=(1000, 10)))

@ray.remote
def f(df):
    # This task will run on a worker and have read only access to the 
    # dataframe. For example, "df.iloc[0][0] = 1" will raise an exception.
    try:
        df.iloc[0][0] = 1
    except ValueError:
        pass
    return df.iloc[0][0]

# Serialize the dataframe with pyarrow and store it in shared memory.
df_id = ray.put(df)

# Run four tasks that have access to the dataframe.
result_ids = [f.remote(df_id) for _ in range(4)]

# Get the results.
results = ray.get(result_ids)

请注意,df_id = ray.put(df) 行可以省略(您可以直接调用f.remote(df))。在这种情况下,df 仍将存储在共享内存中并与工作线程共享,但它将被存储 4 次(每次调用 f.remote(df) 一次) >),效率较低。

关于python - 使用 pyarrow 在工作人员之间共享对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54582073/

相关文章:

python - 跨进程共享对象状态?

python - 优化测试多个 NumPy 数组中的所有行组合

python Pandas : Importing stacked dictionary of lists to create multi-indexed DataFrame

python - pandas read_csv 删除空白行

python - 在具有自己路径的不同 python 可执行文件下生成 multiprocessing.Process

python multiprocessing.Process.terminate - 如何杀死子进程

python - 如何在 Python 3.6 中隐藏 input()?

python - 如何在 Google Colab 中的另一个虚拟机上拍摄和恢复模型训练的快照?

java - Jython - 在 Java 中调用 Python 类

python - 如何使用python选择前X列和后Y列