在特定列分组后查找最早日期
Finding earliest date after groupby a specific column
我有一个如下所示的数据框。
id name tag location date
1 John 34 FL 01/12/1990
1 Peter 32 NC 01/12/1990
1 Dave 66 SC 11/25/1990
1 Mary 12 CA 03/09/1990
1 Sue 29 NY 07/10/1990
1 Eve 89 MA 06/12/1990
: : : : :
n John 34 FL 01/12/2000
n Peter 32 NC 01/12/2000
n Dave 66 SC 11/25/1999
n Mary 12 CA 03/09/1999
n Sue 29 NY 07/10/1998
n Eve 89 MA 06/12/1997
我需要根据 id 列查找位置信息,但有一个条件,只需要最早的日期。例如,id=1 组的最早日期是 01/12/1990,这意味着位置是 FL 和 NC。然后将其应用于所有不同的 id 组以获得前 3 个位置。我已经为我编写了代码。
#Get the earliest date base on id group
df_ear = df.loc[df.groupby('id')['date'].idxmin()]
#Count the occurancees of the location
df_ear['location'].value_counts()
该代码工作得很好,但如果它们具有相同的最早日期,则它不能 return 超过 1 个位置(使用我的第一行代码),例如,id=1 组只会 return FL 代替 FL 和 NC。我想知道如何修复我的代码以包含如果最早日期大于 1 的条件。
谢谢!
使用GroupBy.transform
for Series for minimal date per groups, so possible compare by column Date
in boolean indexing
:
df['date'] = pd.to_datetime(df['date'])
df_ear = df[df.groupby('id')['date'].transform('min').eq(df['date'])]
我有一个如下所示的数据框。
id name tag location date
1 John 34 FL 01/12/1990
1 Peter 32 NC 01/12/1990
1 Dave 66 SC 11/25/1990
1 Mary 12 CA 03/09/1990
1 Sue 29 NY 07/10/1990
1 Eve 89 MA 06/12/1990
: : : : :
n John 34 FL 01/12/2000
n Peter 32 NC 01/12/2000
n Dave 66 SC 11/25/1999
n Mary 12 CA 03/09/1999
n Sue 29 NY 07/10/1998
n Eve 89 MA 06/12/1997
我需要根据 id 列查找位置信息,但有一个条件,只需要最早的日期。例如,id=1 组的最早日期是 01/12/1990,这意味着位置是 FL 和 NC。然后将其应用于所有不同的 id 组以获得前 3 个位置。我已经为我编写了代码。
#Get the earliest date base on id group
df_ear = df.loc[df.groupby('id')['date'].idxmin()]
#Count the occurancees of the location
df_ear['location'].value_counts()
该代码工作得很好,但如果它们具有相同的最早日期,则它不能 return 超过 1 个位置(使用我的第一行代码),例如,id=1 组只会 return FL 代替 FL 和 NC。我想知道如何修复我的代码以包含如果最早日期大于 1 的条件。
谢谢!
使用GroupBy.transform
for Series for minimal date per groups, so possible compare by column Date
in boolean indexing
:
df['date'] = pd.to_datetime(df['date'])
df_ear = df[df.groupby('id')['date'].transform('min').eq(df['date'])]