【发布时间】:2020-12-31 19:13:44
【问题描述】:
我有一个函数,它对每个 DataFrame 列执行一些操作并从中提取较短的序列(在原始代码中进行了一些耗时的计算) 然后在继续下一列之前将其添加到字典中。
最后它从字典中创建一个数据框并操作它的索引。
如何并行化处理每一列的循环?
这是一个不太复杂的可重现代码示例。
import pandas as pd
raw_df = pd.DataFrame({"A":[ 1.1 ]*100000,
"B":[ 2.2 ]*100000,
"C":[ 3.3 ]*100000})
def preprocess_columns(raw_df, ):
df = {}
width = 137
for name in raw_df.columns:
'''
Note: the operations in this loop do not have a deep sense and are just for illustration of the function preprocess_columns. In the original code there are ~ 50 lines of list comprehensions etc.
'''
# 3. do some column operations. (actually theres more than just this operation)
seriesF = raw_df[[name]].dropna()
afterDropping_indices = seriesF.index.copy(deep=True)
list_ = list(raw_df[name])[width:]
df[name]=pd.Series(list_.copy(), index=afterDropping_indices[width:])
# create df from dict and reindex
df=pd.concat(df,axis=1)
df=df.reindex(df.index[::-1])
return df
raw_df = preprocess_columns(raw_df )
【问题讨论】:
-
看起来和
df.drop((range(width)))的结果一样 -
@Johnny 确实如此。抱歉造成误解。这段代码只是一个结构示例,用于指出具体的并行化应该放在哪里。
-
您几乎破解了它,即您可以将
df[name]作为索引号传递并分发到您的处理单元(考虑到您的“做一些操作”是相互独立的)。 -
如果您正在寻找通用的并行实现,值得关注 modin 的 pandas
-
@Gahan 怎么做?我只是想不通如何使用 mp.pool()
标签: python pandas performance parallel-processing multiprocessing