Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
257 views
in Technique[技术] by (71.8m points)

python - Make for loop execute parallely with Pandas columns

Please convert below code to execute parallel, Here I'm trying to map nested dictionary with pandas column values. The below code works perfectly but consumes lot of time. Hence looking to parallelize the for loop(Note: df.replace(Source_Dictionary) also did the job but takes triple the time of below code).

df = pd.DataFrame({'one':['bab'],'two':['abb'],'three':['bb']})
Source_Dictionary = {'one':{'dadd':1,'bab':1.5},
                    'two':{'ab':2},
                    'three':{'cc':1,'bb':3}}
required_columns = ['one','two','three']
def Feature_Map(x):
    df[x] = df[x].map(Source_Dictionary[x]).fillna(0)

for i in required_columns:
    Feature_Map(i)
print(df)
   one  two  three
0  1.5  0.0      3
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To speed up your execution you can use multi processing. Number of processes and its performance depends on the resource provided. Let's suppose you can afford 4 processes to be running in parallel.

Your function:

def Feature_Map(x):
df[x] = df[x].map(Source_Dictionary[x]).fillna(0)

Multi processing:

from multiprocessing.pool import ThreadPool
pool = ThreadPool(processes=4)
for i in required_columns:
    pool.apply_async(Feature_Map, (i))

You can also implement code for waiting till the process has finished execution before exiting.

You can refer to https://docs.python.org/2/library/multiprocessing.html for detailed usage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...