How to apply a function to multiple columns of a Dask Data Frame in parallel?

最后都变了- 提交于 2021-02-18 17:00:20

问题


I have a Dask Dataframe for which I would like to compute skewness for a list of columns and if this skewness exceeds a certain threshold, I correct it using log transformation. I am wondering whether there is a more efficient way of making correct_skewness() function work on multiple columns in parallel by removing the for loop in the correct_skewness() function below:

import dask
import dask.array as da 
from scipy import stats

# Create a dataframe 
df = dask.datasets.timeseries()

df.head()

                      id     name         x         y
timestamp
2000-01-01 00:00:00  1032   Oliver  0.018604  0.089191
2000-01-01 00:00:01  1032  Norbert  0.666689 -0.979374
2000-01-01 00:00:02   991   Victor  0.027691 -0.474660
2000-01-01 00:00:03   979    Kevin  0.320067  0.656949
2000-01-01 00:00:04  1087    Zelda -0.462076  0.513409


def correct_skewness(columns=None, max_skewness=2):
    if columns is None:
        raise ValueError(
            f"columns argument is None. Please set columns argument to a list of columns"
        )


    for col in columns:
        skewness = stats.skew(df[col])
        max_val = df[col].max().compute()
        min_val = df[col].min().compute()

        if abs(skewness) > max_skewness and (max_val > 1 or min_val < 0):
            delta = 1.0
            if min_val < 0:
                delta = max(1, -min_val + 1)
            df[col] = da.log(delta + df[col])
    return df

df = correct_skewness(columns=['x', 'y']) 

回答1:


There are a couple things you can do to improve parallelism in this example:

You can use dask.array.stats.skew rather than statsmodels.skew. You will have to import dask.array.stats explicitly

You can compute the min/max of all columns in one computation

    mins = [df[col].min() for col in cols]
    maxes = [df[col].min() for col in cols]
    skews = [da.stats.skew(df[col]) for col in cols]

    mins, maxes, skews = dask.compute(mins, maxes, skews)

Then you could do your if-logic and apply da.log as appropriate. This still requires two passes over your data, but that should be a nice improvement over what you have now.



来源:https://stackoverflow.com/questions/52117218/how-to-apply-a-function-to-multiple-columns-of-a-dask-data-frame-in-parallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!