我有一个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分组的每个组中选择第一条记录。如果可能的话,如何在黄昏和大熊猫中实现这一目标。
输出:
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.
由于许多答案无法正常工作,请测试并发布答案。
达斯克
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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句