如何使用dask映射列

wis*_*shi 4 python pandas dask

我想在DataFrame列上应用映射.对于熊猫,这是直截了当的:

df["infos"] = df2["numbers"].map(lambda nr: custom_map(nr, hashmap))
Run Code Online (Sandbox Code Playgroud)

这将infos根据custom_map函数写入列,并使用数字中的行作为lambda语句.

使用dask,这并不是那么简单.ddf是一个dask DataFrame.map_partitions相当于在DataFrame的一部分上并行执行映射.

这并没有工作,因为你没有定义一样,在DASK列.

ddf["infos"] = ddf2["numbers"].map_partitions(lambda nr: custom_map(nr, hashmap))
Run Code Online (Sandbox Code Playgroud)

有谁知道如何在这里使用列?我根本不了解他们的API文档.

MRo*_*lin 11

您可以使用.map方法,就像在Pandas中一样

In [1]: import dask.dataframe as dd

In [2]: import pandas as pd

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

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

In [5]: df.x.map(lambda x: x + 1)
Out[5]: 
0    2
1    3
2    4
Name: x, dtype: int64

In [6]: ddf.x.map(lambda x: x + 1).compute()
Out[6]: 
0    2
1    3
2    4
Name: x, dtype: int64
Run Code Online (Sandbox Code Playgroud)

元数据

系统可能会要求您提供meta=关键字.这使dask.dataframe知道函数的输出名称和类型.从map_partitions此处复制docstring :

meta : pd.DataFrame, pd.Series, dict, iterable, tuple, optional

An empty pd.DataFrame or pd.Series that matches the dtypes and 
column names of the output. This metadata is necessary for many 
algorithms in dask dataframe to work. For ease of use, some 
alternative inputs are also available. Instead of a DataFrame, 
a dict of {name: dtype} or iterable of (name, dtype) can be 
provided. Instead of a series, a tuple of (name, dtype) can be 
used. If not provided, dask will try to infer the metadata. 
This may lead to unexpected results, so providing meta is  
recommended. 

For more information, see dask.dataframe.utils.make_meta.
Run Code Online (Sandbox Code Playgroud)

所以在上面的例子中,我的输出将是一个带有name 'x'和dtype 的系列,int我可以做以下任何一个更明确

>>> ddf.x.map(lambda x: x + 1, meta=('x', int))
Run Code Online (Sandbox Code Playgroud)

要么

>>> ddf.x.map(lambda x: x + 1, meta=pd.Series([], dtype=int, name='x'))
Run Code Online (Sandbox Code Playgroud)

这告诉dask.dataframe对我们的函数有什么期望.如果没有给出meta,那么dask.dataframe将尝试在一小段数据上运行你的函数.如果失败,它将引发错误请求帮助.