gpt4 book ai didi

python - 将 lambda 函数应用于 dask 数据框

转载 作者:行者123 更新时间:2023-12-01 08:16:34 26 4
gpt4 key购买 nike

我希望将 lambda 函数应用于 dask 数据帧,以更改列中的标签(如果其小于特定百分比)。我使用的方法适用于 pandas 数据框,但相同的代码不适用于 dask 数据框。代码如下。

df = pd.DataFrame({'A':['ant','ant','cherry', 'bee', 'ant'], 'B':['cat','peach', 'cat', 'cat', 'peach'], 'C':['dog','dog','roo', 'emu', 'emu']})
ddf = dd.from_pandas(df, npartitions=2)

df:

输出:

     A     B      C
0 ant cat dog
1 ant peach dog
2 cherry cat roo
3 bee cat emu
4 ant peach emu
ddf.compute()

输出:

     A     B      C
0 ant cat dog
1 ant peach dog
2 cherry cat roo
3 bee cat emu
4 ant peach emu
list_ = ['B','C']
df.apply(lambda x: x.mask(x.map(x.value_counts(normalize=True))<.5, 'other') if x.name not in list_ else x)

输出:

     A     B      C
0 ant cat dog
1 ant peach dog
2 other cat roo
3 other cat emu
4 ant peach emu

对 dask 数据框执行相同的操作:

ddf.apply(lambda x: x.mask(x.map(x.value_counts(normalize=True))<.5, 'other') if x.name not in list_ else x,axis=1).compute()

输出(给出警告,而不是所需的输出):

/home/michael/env/lib/python3.5/site-packages/dask/dataframe/core.py:3107: UserWarning: `meta` is not specified, inferred from partial data. Please provide `meta` if the result is unexpected.
Before: .apply(func)
After: .apply(func, meta={'x': 'f8', 'y': 'f8'}) for dataframe result
or: .apply(func, meta=('x', 'f8')) for series result
warnings.warn(msg)
A B C
0 other other other
1 other other other
2 other other other
3 other other other
4 other other other

有人可以帮助我获得 dask 数据帧实例所需的输出吗?

谢谢

迈克尔

最佳答案

在 pandas 和 dask 情况下,您没有执行相同的操作:对于后者,您有 axis=1,因此您最终会替换给定 中出现次数少于两次的任何值>行,这是全部。

如果更改为 axis=0,您将看到出现异常。这是因为要计算第一个分区,您还需要将整个数据帧传递给 lambda 函数 - 否则如何获得 value_counts?

解决您的问题的方法是单独获取值计数。您可以显式计算它(结果很小)或将其传递给 lambda。此外请注意,走这条路意味着您可以避免使用 apply 来支持 map 并使事情更加明确。这里我专门挑了一栏,大家可以循环。

vc = ddf.A.value_counts().compute()
vc /= vc.sum() # because dask's value_count doesn't normalise

def simple_map(df):
df['A'] = df['A'].map(lambda x: x if vc[x] > 0.5 else 'other')
return df

ddf.map_partitions(simple_map, meta=df[:0]).compute()

关于python - 将 lambda 函数应用于 dask 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54955833/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com