Python中使用P的多处理

2024-04-16 16:56:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用Python在数据帧上并行化一个函数。我看了一些教程,找到了一些代码,我已经根据我的需要进行了调整。当我执行map函数时,程序冻结。代码似乎是可靠的。我不知道是什么问题。在

import pandas as pd
import numpy as np
from multiprocessing import cpu_count, Pool

attributes1 = pd.read_csv('attributes1.csv')


def replace_data(data):
    for i in range(0, len(data.index)):
        temp = data.iloc[i, 1]
        temp = temp.replace('in.', 'inch')
        data.iloc[i, 1] = temp
    return data

num_partitions = 10 #number of partitions to split dataframe
num_cores = cpu_count() #number of cores on your machine

def parallelize_dataframe(df, func):
    df_split = np.array_split(df, num_partitions)
    pool = Pool(num_cores)
    df = pd.concat(pool.map(func, df_split))
    pool.close()
    pool.join()
    return df

df1 = parallelize_dataframe(attributes1, replace_data)

Tags: 函数代码importdataframedfdatacorestemp
2条回答

您可能正在使用windows,要修复它,您需要^{}

from multiprocessing cpu_count, Pool, freeze_support

...

if __name__ == '__main__':
    freeze_support()
    df1 = parallelize_dataframe(attributes1, replace_data)

这只是Windows用户的问题。首先,我创建了另一个.py文件来命名它帮助.py我有替换数据功能

def replace_data(data):
    for i in range(0, len(data.index)):
        temp = data.iloc[i, 1]
        temp = temp.replace('in.', 'inch')
        data.iloc[i, 1] = temp
    return data

然后我将函数导入到main.py文件中。在

^{pr2}$

我还添加了if __name__ == '__main__':,现在程序运行顺利。在

相关问题 更多 >