Tôi có một DataFrame gấu trúc với dữ liệu log:Pandas, groupby và tìm tối đa trong nhóm, giá trị trở lại và đếm
host service
0 this.com mail
1 this.com mail
2 this.com web
3 that.com mail
4 other.net mail
5 other.net web
6 other.net web
Và tôi muốn tìm dịch vụ trên tất cả các máy chủ cung cấp cho các lỗi nhất:
host service no
0 this.com mail 2
1 that.com mail 1
2 other.net web 2
Giải pháp duy nhất tôi tìm thấy được nhóm theo máy chủ và dịch vụ, sau đó lặp lại trên mức 0 của chỉ mục.
Ai đó có thể đề xuất phiên bản ngắn hơn, tốt hơn không? mà không có Iteration?
df = df_logfile.groupby(['host','service']).agg({'service':np.size})
df_count = pd.DataFrame()
df_count['host'] = df_logfile['host'].unique()
df_count['service'] = np.nan
df_count['no'] = np.nan
for h,data in df.groupby(level=0):
i = data.idxmax()[0]
service = i[1]
no = data.xs(i)[0]
df_count.loc[df_count['host'] == h, 'service'] = service
df_count.loc[(df_count['host'] == h) & (df_count['service'] == service), 'no'] = no
đầy đủ đang https://gist.github.com/bjelline/d8066de66e305887b714
Thành ngữ này có thể làm cho một bổ sung tốt đẹp để API groupby: https://github.com/pydata/pandas/issues/8717 – Jeff