我正在尝试加速 Python 3 中的一些多处理代码。我有一个大的只读 DataFrame
和一个根据读取值进行一些计算的函数。
我尝试解决在同一文件中编写函数并共享大 DataFrame
的问题,如您在此处看到的。这种方法不允许将进程函数移动到另一个文件/模块,并且访问函数范围之外的变量有点奇怪。
import pandas as pd
import multiprocessing
def process(user):
# Locate all the user sessions in the *global* sessions dataframe
user_session = sessions.loc[sessions['user_id'] == user]
user_session_data = pd.Series()
# Make calculations and append to user_session_data
return user_session_data
# The DataFrame users contains ID, and other info for each user
users = pd.read_csv('users.csv')
# Each row is the details of one user action.
# There is several rows with the same user ID
sessions = pd.read_csv('sessions.csv')
p = multiprocessing.Pool(4)
sessions_id = sessions['user_id'].unique()
# I'm passing an integer ID argument to process() function so
# there is no copy of the big sessions DataFrame
result = p.map(process, sessions_id)
我尝试过的事情:
- 传递 DataFrame 而不是整数 ID 参数,以避免
sessions.loc...
代码行。这种方法会大大减慢脚本的速度。
此外,我还查看了 How to share pandas DataFrame object between processes?但没有找到更好的方法。
最佳答案
您可以尝试将流程定义为:
def process(sessions, user):
...
并将其放在您喜欢的任何地方。
然后当您调用p.map
时,您可以使用functools.partial
函数,允许增量指定参数:
from functools import partial
...
p.map(partial(process, sessions), sessions_id)
这不会使处理速度减慢太多并能解决您的问题。
请注意,您也可以在没有 partial
的情况下执行相同的操作,使用:
p.map(lambda id: process(sessions,id)), sessions_id)
关于python - 访问多处理映射中的共享数据帧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35177768/