【问题标题】:How to map a column with dask如何用 dask 映射列
【发布时间】:2017-02-22 12:18:43
【问题描述】:

我想在 DataFrame 列上应用映射。对于 Pandas,这很简单:

df["infos"] = df2["numbers"].map(lambda nr: custom_map(nr, hashmap))

这会根据custom_map 函数写入infos 列,并将行数用于lambda 语句。

有了dask,这并不是那么简单。 ddf 是一个 dask DataFrame。 map_partitions 相当于在部分DataFrame上并行执行映射。

不起作用,因为您没有在 dask 中定义类似的列。

ddf["infos"] = ddf2["numbers"].map_partitions(lambda nr: custom_map(nr, hashmap))

有人知道我如何在这里使用列吗?我根本不理解他们的API documentation

【问题讨论】:

  • Dask 当前版本 1.2 已经可以接受上述语法:df['new_col']=df['col2].map_parttion(some_func)

标签: python pandas dask


【解决方案1】:

您可以使用 .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

元数据

您可能会被要求提供meta= 关键字。这让 dask.dataframe 知道函数的输出名称和类型。在此处从map_partitions 复制文档字符串:

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.

所以在上面的示例中,我的输出将是一个名称为 'x' 和 dtype int 的系列,我可以执行以下任一操作以更明确

>>> ddf.x.map(lambda x: x + 1, meta=('x', int))

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

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

【讨论】:

  • 在我的情况下,元数据推断失败,请提供 meta 关键字 - 在某些情况下似乎这是必需的...
  • meta = int 是否也能正常工作?虽然文档字符串中似乎没有提到它,但我想我在 github 上的某个地方看到了它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-24
  • 2011-09-11
相关资源
最近更新 更多