【问题标题】:Finding the count, earliest date and latest date for each name in Python在 Python 中查找每个名称的计数、最早日期和最晚日期
【发布时间】:2016-06-09 00:38:12
【问题描述】:

假设我有如下数据,包括姓名、班级和日期

Name    class   Date
A   7th grade   1/1/2016
A   7th grade   1/2/2016
A   7th grade   1/3/2016
A   7th grade   1/4/2016
A   7th grade   1/5/2016
A   7th grade   1/6/2016
A   7th grade   1/7/2016
B   8th grade   1/8/2016
B   8th grade   1/9/2016
B   8th grade   1/10/2016
C   9th grade   1/11/2016
C   9th grade   1/12/2016
C   9th grade   1/13/2016
C   9th grade   1/14/2016
C   9th grade   1/15/2016
C   9th grade   1/16/2016
C   9th grade   1/17/2016
C   9th grade   1/18/2016
C   9th grade   1/19/2016
C   9th grade   1/20/2016
C   9th grade   1/21/2016
C   9th grade   1/22/2016

我正在寻找一个输出,它可以为我提供每个名称的值计数、它们各自的等级以及最早日期和最晚日期。我的输出是,

Name grade   count earlydate latestdate
A   7thgrade   7    1/1/2016  1/7/2016
B   8th grade  3    1/8/2016  1/10/2016
C   9th grade  12   1/11/2016 1/22/2016

我可以通过,找到每个名字的计数,

data.groupby('name','grade').count()
or
data.groupby('name','grade').size()

但无法在日期列中找到最早日期和最晚日期。

谁能帮我解决这个问题?

【问题讨论】:

  • 你用的是什么数据库?尝试在 sql 中使用 Joins 和 MIN/MAX 函数
  • 我有这个作为 python 数据框。需要在python中做到这一点
  • @clemkoa 感谢您的链接。但在那个链接中,日期是索引而不是列,也不会返回我想要的结果。我想要一个数据框,它会给出如图所示的详细信息

标签: python


【解决方案1】:

Max and Min date in pandas groupby

可能是这样的:

data.groupby('name','grade').agg({'date' : [np.min, np.max]}).count()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-13
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    相关资源
    最近更新 更多