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

旧街凉风 提交于 2019-12-14 00:34:57

问题


If I have a Pandas dataframe, and a column that is a datetime type, I can get the year as follows:

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

With a dask dataframe, that does not work. If I compute first, like this:

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

I get ValueError: Not all divisions are known, can't align partitions. Please useset_indexorset_partitionto set the index.

But if I do:

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

it works fine!

So how do I get the year (or week) of a datetime series in a dask dataframe?


回答1:


The .dt datetime namespace is present on Dask series objects. Here is a self-contained of its use:

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'] = df['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


来源:https://stackoverflow.com/questions/42797328/getting-year-and-week-from-a-datetime-series-in-a-dask-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!