我有一個如下所示的資料框
stu_id,Mat_grade,sci_grade,eng_grade
1,A,C,A
1,A,C,A
1,B,C,A
1,C,C,A
2,D,B,B
2,D,C,B
2,D,D,C
2,D,A,C
tf = pd.read_clipboard(sep=',')
我的目標是
a) 找出一個學生有多少不同的獨特成績Mat_grade,sci_grade以及eng_grade
所以,我嘗試了以下
tf['mat_cnt'] = tf.groupby(['stu_id'])['Mat_grade'].nunique()
tf['sci_cnt'] = tf.groupby(['stu_id'])['sci_grade'].nunique()
tf['eng_cnt'] = tf.groupby(['stu_id'])['eng_grade'].nunique()
但這并沒有提供預期的輸出。因為,我有超過 100K 的唯一 ID,任何高效而優雅的解決方案都非常有幫助
我希望我的輸出如下

uj5u.com熱心網友回復:
您可以在串列中指定列名稱,并使用以下命令進行列cols呼叫:DataFrameGroupBy.nuniquerename
cols = ['Mat_grade','sci_grade', 'eng_grade']
new = ['mat_cnt','sci_cnt','eng_cnt']
d = dict(zip(cols, new))
df = tf.groupby(['stu_id'], as_index=False)[cols].nunique().rename(columns=d)
print (df)
stu_id mat_cnt sci_cnt eng_cnt
0 1 3 1 1
1 2 1 4 2
另一個想法是使用命名聚合:
cols = ['Mat_grade','sci_grade', 'eng_grade']
new = ['mat_cnt','sci_cnt','eng_cnt']
d = {v: (k,'nunique') for k, v in zip(cols, new)}
print (d)
{'mat_cnt': ('Mat_grade', 'nunique'),
'sci_cnt': ('sci_grade', 'nunique'),
'eng_cnt': ('eng_grade', 'nunique')}
df = tf.groupby(['stu_id'], as_index=False).agg(**d)
print (df)
stu_id mat_cnt sci_cnt eng_cnt
0 1 3 1 1
1 2 1 4 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/479957.html
標籤:Python 熊猫 列表 数据框 熊猫-groupby
上一篇:根據字串提取路徑名
