Python数据帧-如何在此处应用线程/多处理来加快速度

Python数据帧-如何在此处应用线程/多处理来加快速度,python,python-3.x,pandas,dataframe,Python,Python 3.x,Pandas,Dataframe,我有一个包含数百万行的DataFrame,我必须对每行的col_1和col_2执行一个函数。 请参见下面的示例。假设每个函数需要2秒,我有3行,所以目前需要6秒。我想在这里使用线程,将时间减少到2秒。我该怎么办 import pandas as pd import time def add(a,b): sum = a+b time.sleep(2) #just to show that in reality my function takes times print("

我有一个包含数百万行的
DataFrame
,我必须对每行的
col_1
col_2
执行一个函数。 请参见下面的示例。假设每个函数需要2秒,我有3行,所以目前需要6秒。我想在这里使用线程,将时间减少到2秒。我该怎么办

import pandas as pd
import time

def add(a,b):
    sum = a+b
    time.sleep(2) #just to show that in reality my function takes times
    print("sum of %d and %d is %d" %(a, b, sum))

data = [[10,10],[9,12],[100,13]]
df = pd.DataFrame(data,columns=['col_1','col_2'])

start_time = time.time()
df.apply(lambda x: add(x.col_1, x.col_2), axis=1)
print("--- %s seconds ---" % (time.time() - start_time))

好的,谢谢大家。异步方法奏效了

import pandas as pd
import time
from multiprocessing.dummy import Pool

pool_size = 5

pool = Pool(pool_size)


def add(a,b):
    sum = a+b
    time.sleep(2) #just to show that in reality my function takes times
    print("sum of %d and %d is %d" %(a, b, sum))

data = [[10,10],[9,12],[100,13]]
df = pd.DataFrame(data,columns=['col_1','col_2'])

start_time = time.time()
for ind in df.index:
     pool.apply_async(add, args=(df['col_1'][ind], df['col_2'][ind],))
pool.close()
pool.join()



print("--- %s seconds ---" % (time.time() - start_time))

您确定您的问题没有解决方案,您必须编写一个函数来处理每一行吗?为什么不发布一个关于你想在函数中实现什么的问题,也许有人会找到一个比编写一个函数来使用
apply
更好的解决方案。apply
只是隐藏了一个for循环,迭代非常慢。许多操作在C库中是本机多处理的。您最好的选择是找到一种使用pandas API尽可能多地进行计算的方法。我的函数非常复杂,输入是API端点,函数涉及API请求、执行一些操作、一些断言和很多事情。@SaurabhShrivastava,在这种情况下,您的函数会执行文件I/O,网络I/O-是的,我将应用线程或异步方法