This is the code I use to parrellize an apply function on the lines of a pandas.DataFrame object:
from multiprocessing import cpu_count, Pool
from functools import partial
def parallel_applymap_df(df: DataFrame, func, num_cores=cpu_count(),**kargs):
partitions = np.linspace(0, len(df), num_cores + 1, dtype=np.int64)
df_split = [df.iloc[partitions[i]:partitions[i + 1]] for i in range(num_cores)]
pool = Pool(num_cores)
series = pd.concat(pool.map(partial(apply_wrapper, func=func, **kargs), df_split))
pool.close()
pool.join()
return series
It's works with a subsamples of 200 000 rows, but when i try on the full 200 000 000 examples, i get the following error message:
~/anaconda3/lib/python3.6/site-packages/multiprocess/connection.py in _send_bytes(self, buf)
394 n = len(buf)
395 # For wire compatibility with 3.2 and lower
—> 396 header = struct.pack("!i", n)
397 if n > 16384:
398 # The payload is large so Nagle's algorithm won't be triggered
error: 'i' format requires -2147483648 <= number <= 2147483647
Generated by the line:
series = pd.concat(pool.map(partial(apply_wrapper, func=func, **kargs), df_split))
It's very weird because a slightly different version that I use to parallelize operations that are not vectorized in pandas (like Series.dt.time) works on the same number of rows. That's version for exampes works:
def parallel_map_df(df: DataFrame, func, num_cores=cpu_count()):
partitions = np.linspace(0, len(df), num_cores + 1, dtype=np.int64)
df_split = [df.iloc[partitions[i]:partitions[i + 1]] for i in range(num_cores)]
pool = Pool(num_cores)
df = pd.concat(pool.map(func, df_split))
pool.close()
pool.join()
return df