![](/img/trans.png)
[英]Python pandas dataframe: find max for each unique values of an another column
[英]pandas: How to find the max n values for each category in a column
我有一個巨大的市政圖書館目錄數據集,包括書名,它所在的圖書館,圖書館的自治市鎮以及借出的次數。
我想為每個社區找到最受歡迎的三本書。
理想情況下,我會得到這樣的東西:
Borough Title Total_loans
A Book1 35615
A Book2 34895
A Book3 2548
B Book1 6541
B Book2 5425
等等
這是我能夠得到的最接近的,但結果數據框架沒有按行政區划分,難以閱讀。
import pandas as pd
df = pd.DataFrame({"borough":["A", "B", "B", "A", "A"], "title":["Book2", "Book1", "Book2", "Book2", "Book1"], "total_loans":[4, 48, 46, 78, 15]})
top_boroughs = df.groupby(['borough','title'])
top_boroughs.aggregate(sum).sort(['total_loans','title'], ascending=False)
謝謝你的幫助。
簡而言之:
df.groupby(level=[0,1]).sum().reset_index().sort_values(['borough', 'total_loans'], ascending=[1,0]).groupby('borough').head(3)
步驟:
3
個 這兩者都優於公認的答案
concat
迭代擴展數據幀相比,浪費內存 我的輸出(使用head(1)
因為測試數據每組只有2
行:
Out[484]:
borough title total_loans
1 A Book2 82
2 B Book1 48
這樣的事情:
t = df.groupby(['borough', 'title']).sum()
t.sort('total_loans', ascending=True)
t = t.groupby(level=[0,1]).head(3).reset_index()
t.sort(['borough', 'title'], ascending=(True, False)) #not sure if this is necessary, tough to tell with limited data, but just in case...
'''
Created on Jul 30, 2014
class TopX():
def __init__(self, top,sortFunction):
self.topX=top
self.sortFunction=sortFunction
self.data=[]
def addNewItem(self,item):
self.data.append(item)
self.data.sort( key=self.sortFunction,reverse=True)
self.data=self.data[:self.topX]
def getMax(self):
return self.data
def runMe():
top = TopX(3, lambda x:int(x[2]))
with open("lib.txt","r") as f:
string= f.readlines()
for line in string:
data= [x.strip() for x in line.split(' ')]
top.addNewItem(data)
print top.getMax()
if __name__ == '__main__':
runMe()
使用格式的輸入文件:
A Book1 1
A Book2 10
A Book3 3
B Book1 7
B Book2 5
給出結果:
[['A', 'Book2', '10'], ['B', 'Book1', '7'], ['B', 'Book2', '5']]
如果您稍后需要調整標准,則可以指定熱門書籍和排序鍵的數量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.