【问题标题】:Using Dask to_datetime and Pandas date offsets使用 Dask to_datetime 和 Pandas 日期偏移
【发布时间】:2021-08-18 14:58:57
【问题描述】:

我有一个函数,它增加一个带有偏移量的 yyyy-mm 格式日期,以便它从下个月的第一天开始。以前我使用过 Pandas pd.to_datetime 和 pd.offsets.MonthBegin 函数来执行此操作,但是我正在尝试将其应用于 Dask。据我所知,虽然 Dask 确实有一个 to_datetime 函数,但它没有一个与 Pandas 执行相同的偏移函数。话虽如此,我尝试结合这两种方法(使用 dd.to_datetime 和 pd.offsets.MonthBegin)并观察到我想要的结果而没有任何错误。我的问题是,这种方法是否推荐/可靠,还是有更好的方法可以只使用 Dask 函数?

产生一些例子的代码如下:

import pandas as pd
import dask.dataframe as dd
from dask.distributed import Client

# Setup cluster
client = Client()

# create test dataframe

test_dates = ["2019-01",
              "2019-02",
              "2019-03",
              "2019-04",
              "2019-05",
              "2019-06",
              "2019-07",
              "2019-08",
              "2019-09",
              "2019-10",
              "2019-11",
              "2019-12"]

df_a = pd.DataFrame(test_dates, columns=['test_month'])
ddf_a = dd.from_pandas(df_a, npartitions=4)

ddf_a["test_month_updated"] = (dd.to_datetime(ddf_a["test_month"].str[0:4] + ddf_a["test_month"].str[-2:] + '01') + pd.offsets.MonthBegin(1)).dt.strftime('%Y%m%d')

ddf_a.compute()

【问题讨论】:

    标签: python pandas dask dask-dataframe


    【解决方案1】:

    您可以使用 Dask 的 map_partitions,它将在每个分区上映射一个函数,即每个 pandas DataFrame。参考文档:https://docs.dask.org/en/latest/generated/dask.dataframe.DataFrame.map_partitions.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-11-18
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 2020-08-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多