我有一个包含以下格式的 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 和 pandas 中实现这一点。
输出:
ID | Value | Date
-----------------------
1. | ABD. | 2019-10-12
2. | CDE. | 2019-01-08
3. | DEF. | NaT
我尝试了什么:
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.
请测试并发布答案,因为许多答案没有按预期工作。