我有一個DF,如下所示:Date Bought | Fruit2018-01 Apple2018-02 Orange2018-02 Orange2018-02 Lemon我希望按“購買日期”和“水果”對數據進行分組,并計算出現次數。預期結果:Date Bought | Fruit | Count2018-01 Apple 12018-02 Orange 22018-02 Lemon 1我得到的:Date Bought | Fruit | Count2018-01 Apple 12018-02 Orange 2 Lemon 1使用的代碼:Initial attempt:df.groupby(['Date Bought','Fruit'])['Fruit'].agg('count')#2df.groupby(['Date Bought','Fruit'])['Fruit'].agg('count').reset_index()ERROR: Cannot insert Fruit, already exists#3df.groupby(['Date Bought','Fruit'])['Fruit'].agg('count').reset_index(inplace=True)ERROR: Type Error: Cannot reset_index inplace on a Series to create a DataFrame文檔顯示 groupby 函數返回“groupby 對象”,而不是標準 DF。如何按上述方式對數據進行分組并保留 DF 格式?
1 回答

子衿沉夜
TA貢獻1828條經驗 獲得超3個贊
這里的問題是,通過重置索引,你最終會得到2個同名的列。因為使用是可能的設置參數,Series.reset_index:Seriesname
df1 = (df.groupby(['Date Bought','Fruit'], sort=False)['Fruit']
.agg('count')
.reset_index(name='Count'))
print (df1)
Date Bought Fruit Count
0 2018-01 Apple 1
1 2018-02 Orange 2
2 2018-02 Lemon 1
添加回答
舉報
0/150
提交
取消