从 dask 数据框中的日期时间系列获取年和周?

Getting year and week from a datetime series in a dask dataframe?

如果我有一个 Pandas 数据框和一个日期时间类型的列,我可以按如下方式获取年份:

df['year'] = df['date'].dt.year

对于 dask 数据框,这是行不通的。如果我先计算,像这样:

df['year'] = df['date'].compute().dt.year

我得到ValueError: Not all divisions are known, can't align partitions. Please useset_indexorset_partitionto set the index.

但如果我这样做:

df['date'].head().dt.year

它工作正常!

那么如何在 dask 数据框中获取日期时间系列的年份(或周)?

.dt 日期时间命名空间存在于 Dask 系列对象上。下面是它的用法自成一体:

In [1]: import pandas as pd

In [2]: df = pd.util.testing.makeTimeSeries().to_frame().reset_index().head(10)

In [3]: df  # some pandas data to turn into a dask.dataframe
Out[3]: 
       index         0
0 2000-01-03 -0.034297
1 2000-01-04 -0.373816
2 2000-01-05 -0.844751
3 2000-01-06  0.924542
4 2000-01-07  0.507070
5 2000-01-10  0.216684
6 2000-01-11  1.191743
7 2000-01-12 -2.103547
8 2000-01-13  0.156629
9 2000-01-14  1.602243

In [4]: import dask.dataframe as dd

In [5]: ddf = dd.from_pandas(df, npartitions=3)

In [6]: ddf['year'] = ddf['index'].dt.year  # use the .dt namespace

In [7]: ddf.head()
Out[7]: 
       index         0  year
0 2000-01-03 -0.034297  2000
1 2000-01-04 -0.373816  2000
2 2000-01-05 -0.844751  2000
3 2000-01-06  0.924542  2000