Dask 数据框:获取每个排序组的第一行
Dask dataframe: Get first row of each sorted group
我有一个包含以下格式的 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
我试过的:
使用:Get the Row(s) which have the max count in groups using 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.
请测试并 post 答案,因为许多答案没有按预期工作。
达斯克
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]
的最大日期)
Pandas
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
我有一个包含以下格式的 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
我试过的:
使用:Get the Row(s) which have the max count in groups using 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.
请测试并 post 答案,因为许多答案没有按预期工作。
达斯克
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]
的最大日期)
Pandas
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