Dask数据帧:获取每个排序组的第一行



我有一个包含以下格式的dask数据帧:

import pandas as pd
import numpy as np
import dask.dataframe as dd
df = pd.DataFrame({'ID': [1, 1, 2, 3], 'Value': ['ABC', 'ABD', 'CDE', 'DEF'], 'Date': ['2020-10-10', '2019-10-12', '2019-01-08', np.nan]})
ddf = dd.from_pandas(df, npartitions=2)
ddf['Date'] = dd.to_datetime(ddf['Date'], dayfirst=True) # Convert to proper dtype
ddf.head()

输出:

| ID | Value | Date
-------------------------
0 | 1. | ABC.  | 2020-10-10
1 | 1. | ABD.  | 2019-10-12
2 | 2. | CDE.  | 2019-01-08
3 | 3. | DEF.  | NaT

我需要在每组中选择第一条记录,按日期排序,按ID分组。如何在dask和panda中实现这一点(如果可能的话(。

输出:

ID | Value | Date
-----------------------
1. | ABD.  | 2019-10-12
2. | CDE.  | 2019-01-08
3. | DEF.  | NaT

我尝试了什么:

使用:使用groupby 获取组中计数最大的行

ddf.set_index('Date').drop_duplicates('ID').head()
# Error: TypeError: '<' not supported between instances of 'NoneType' and 'int'
ddf.loc[ddf.groupby('ID')['Date'].idxmax()].head()
# Error: ValueError: Not all divisions are known, can't align partitions. Please use `set_index` to set the index.

请测试并公布答案,因为许多答案没有按预期工作。

Dask

ddf.set_index(ddf.Date.fillna(pd.to_datetime('2262-04-11'))).drop_duplicates('ID').set_index('ID').reset_index().compute()
#   ID Value       Date
#0   1   ABD 2019-10-12
#1   2   CDE 2019-01-08
#2   3   DEF        NaT

(2262-04-11是datetime64[ns]的最长日期(

熊猫

df.sort_values(['ID', 'Date']).drop_duplicates('ID')
#   ID Value        Date
#1   1   ABD  2019-10-12
#2   2   CDE  2019-01-08
#3   3   DEF         NaN

最新更新