我有一个200个DataFrames的列表,我正在尝试应用一个函数,但是。我正在尝试在python中应用并行函数来加快速度,但无法获得期望的结果。下面是我的代码data是具有相同列和行但不同值的DataFrame的列表
import pandas as pd
import multiprocessing as mp
def maxloc(data):
data['loc_max'] = np.zeros(len(data))
for i in range(1,len(data)-1):
if data['value'][i] >= data['value'][i-1] and data['value'][i] >= data['value'][i+1]:
data['loc_max'][i] = 1
return data
pool = mp.Pool(mp.cpu_count())
results = pool.map(maxloc, [row for row in data])
pool.close()
pool.join()
下面是maxloc的一个实现,它使用scipy.signal.argrelextrema,速度快得多(在本例中是1000多倍(:
import pandas as pd
from scipy.signal import argrelextrema
np.random.seed(42)
def maxloc(data):
data['loc_max'] = np.zeros(len(data))
for i in range(1,len(data)-1):
if data['value'][i] >= data['value'][i-1] and data['value'][i] >= data['value'][i+1]:
data['loc_max'][i] = 1
return data
def maxloc_faster(data):
loc_opt_ind = argrelextrema(df.value.to_numpy(), np.greater)
loc_max = np.zeros(len(data))
loc_max[loc_opt_ind] = 1
data['loc_max'] = loc_max
return data
让我们测试一下
values = np.random.rand(10000)
df = pd.DataFrame({'value': values})
np.all(maxloc_faster(df).loc_max == maxloc(df).loc_max)
# True
%timeit maxloc(df)
# 672 ms ± 39.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit maxloc_faster(df)
# 268 µs ± 12.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)