簡體   English   中英

根據條件過濾數據幀行 Pandas

[英]Filter data-frame rows based on conditions Pandas

我有一個這樣的數據框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獲取所有唯一的Date

Output 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的唯一Date計數

Student_id   unique_date_count
1000101        3
1000102        2
1000103        1

編輯:由於唯一的子項目,我不能刪除任何行,所以我怎樣才能獲得每個Student_id的唯一日期及其計數

我在這里先向您的幫助表示感謝!

使用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_new=df.drop_duplicates()

其次,你可以做value_counts

df_new['Student_id'].value_counts()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM