如何在Dask中进行行处理和项目分配


问题内容

相似的未解决问题:Dask
DataFrame的逐行处理

我正在使用数百万行长的数据框,因此现在我正在尝试并行执行所有数据框操作。我需要转换为Dask的一种这样的操作是:

 for row in df.itertuples():                                                                                                                                                                                                         
     ratio = row.ratio                                                                                                                                                                                                                     
     tmpratio = row.tmpratio                                                                                                                                                                                                                                                                                                                                                                                                 
     tmplabel = row.tmplabel                                                                                                                                                                                                               
     if tmpratio > ratio:                                                                                                                                                                                                                  
         df.loc[row.Index,'ratio'] = tmpratio                                                                                                                                                                                        
         df.loc[row.Index,'label'] = tmplabel

在Dask中按索引设置值或在行中有条件设置值的合适方法是什么?由于.loc不支持DASK项任务,似乎没有成为set_valueat[]或者iat[]在DASK无论是。

我尝试将map_partitionsassign一起使用,但是我没有看到在行级执行条件赋值的任何功能。


问题答案:

Dask数据框不支持有效的迭代或行分配。通常,这些工作流很难很好地扩展。它们在熊猫本身中也相当慢。

相反,您可以考虑使用Series.where方法。这是一个最小的示例:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({'x': [1, 2, 3], 'y': [3, 2, 1]})

In [3]: import dask.dataframe as dd

In [4]: ddf = dd.from_pandas(df, npartitions=2)

In [5]: ddf['z'] = ddf.x.where(ddf.x > ddf.y, ddf.y)

In [6]: ddf.compute()
Out[6]:
   x  y  z
0  1  3  3
1  2  2  2
2  3  1  3