首页 文章

Python Dask map_partitions

提问于
浏览
0

可能是这个question的延续,使用map_partitions的dask docs示例 .

import dask.dataframe as dd
df = pd.DataFrame({'x': [1, 2, 3, 4, 5],     'y': [1., 2., 3., 4., 5.]})
ddf = dd.from_pandas(df, npartitions=2)

from random import randint

def myadd(df):
    new_value = df.x + randint(1,4)
    return new_value

res = ddf.map_partitions(lambda df: df.assign(z=myadd)).compute()
res

在上面的代码中,randint只被调用一次,而不是像我期望的那样每行调用一次 . 怎么会?

输出:

X Y Z.

1 1 4

2 2 5

3 3 6

4 4 7

5 5 8

1 回答

  • 1

    如果您在原始pandas数据帧上执行了相同的操作( df.x + randint(1,4) ),则只能获得一个随机数,并添加到该列的每个先前值 . 这与pandas情况完全相同,只是它为每个分区调用一次 - 这就是 map_partition 所做的 .

    如果你想为每一行添加一个新的随机数,你应该首先考虑如何用熊猫实现这一目标 . 我可以马上想到两个:

    df.x.map(lambda x: x + random.randint(1, 4))
    

    要么

    df.x + np.random.randint(1, 4, size=len(df.x))
    

    如果用其中一个替换 newvalue = 行,它将按预期工作 .

相关问题