【问题标题】:Filter data-frame rows based on conditions Pandas根据条件过滤数据框行 Pandas
【发布时间】:2021-02-23 09:56:47
【问题描述】:

我有一个这样的数据框df

[Date:mm/dd/yyyy]

Date           Student_id    subject     Subject_Scores
11/30/2020     1000101       Math           70
11/25/2020     1000101       Physics        75
12/02/2020     1000101       Biology        60
11/25/2020     1000101       Chemistry      49
11/25/2020     1000101       English        80
12/02/2020     1000101       Sociology      50
11/25/2020     1000102       Physics        80
11/25/2020     1000102       Math           90
12/15/2020     1000102       Chemistry      63
12/15/2020     1000103       English        71

如何获得每个 Student_id 的所有唯一 Dates。

输出date_df:

Date           Student_id
11/30/2020     1000101
11/25/2020     1000101
12/02/2020     1000101
11/25/2020     1000102
12/15/2020     1000102
12/15/2020     1000103

另外,我需要每个Student_id 的唯一Dates 计数

Student_id   unique_date_count
1000101        3
1000102        2
1000103        1

编辑:由于唯一的子项目,我无法删除任何行,所以我如何才能获得每个 Student_id 的唯一日期及其计数

提前感谢您的帮助!

【问题讨论】:

    标签: python python-3.x pandas dataframe data-analysis


    【解决方案1】:

    使用DataFrame.drop_duplicates:

    df1 = df[['Date','Student_id']].drop_duplicates()
    print (df1)
             Date  Student_id
    0  11/30/2020     1000101
    1  11/25/2020     1000101
    2  12/02/2020     1000101
    6  11/25/2020     1000102
    8  12/15/2020     1000102
    9  12/15/2020     1000103
    

    然后Series.value_counts:

    s = df1['Student_id'].value_counts()
    print (s)
    1000101    3
    1000102    2
    1000103    1
    Name: Student_id, dtype: int64
    

    最后如果需要DataFrame添加Series.rename_axisSeries.reset_index

    df2 = s.rename_axis('Student_id').reset_index(name='unique_date_count')
    print (df2)
       Student_id  unique_date_count
    0     1000101                  3
    1     1000102                  2
    2     1000103                  1
    

    【讨论】:

    • 嗨,除了df.drop_duplicates() 之外,还有其他可能吗?由于我的扩展数据集有其他信息(即每个 Student_id 的唯一 subject),所以我不能删除重复的行。
    • @PNyak - 你觉得df[['Date','Student_id']].drop_duplicates() 吗?
    【解决方案2】:

    首先,你需要做:

    df_new=df.drop_duplicates()
    

    第二,可以value_counts

    df_new['Student_id'].value_counts()
    

    【讨论】:

      猜你喜欢
      • 2020-08-29
      • 1970-01-01
      • 2017-12-15
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2019-08-17
      • 1970-01-01
      • 2018-03-27
      相关资源
      最近更新 更多