2014-11-02 12 views
7

Ben günlük verilerine sahip bir pandalar DataFrame vardır:Pandalar, GroupBy ve gruplar halinde bulma maksimum, dönen değer ve saymak

 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 

Ve çoğu hataları veren her ana bilgisayarda hizmeti bulmak istiyoruz:

 host service no 
0 this.com mail 2 
1 that.com mail 1 
2 other.net  web 2 

Bulduğum tek çözüm, ana makine ve hizmet tarafından gruplandırıldı ve dizininin 0 düzeyinin üzerinde yinelendi.

Herkes daha iyi, daha kısa bir sürüm önerebilir mi? yineleme olmadan?

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 

df göz önüne alındığında, tam kod https://gist.github.com/bjelline/d8066de66e305887b714

cevap

4

, bir sonraki adım, tek başına host değeri ve idxmax ile
agregat grubu etmektir. Bu size 'un en büyük servis değerine karşılık geldiği endeksi verir. https:/

import numpy as np 
import pandas as pd 

df_logfile = pd.DataFrame({ 
    'host' : ['this.com', 'this.com', 'this.com', 'that.com', 'other.net', 
       'other.net', 'other.net'], 
    'service' : ['mail', 'mail', 'web', 'mail', 'mail', 'web', 'web' ] }) 

df = df_logfile.groupby(['host','service'])['service'].agg({'no':'count'}) 
mask = df.groupby(level=0).agg('idxmax') 
df_count = df.loc[mask['no']] 
df_count = df_count.reset_index() 
print("\nOutput\n{}".format(df_count)) 

 host service no 
0 other.net  web 2 
1 that.com mail 1 
2 this.com mail 2 
+0

hale getirebileceğini Bu deyim GroupBy API için güzel bir yanı DataFrame verir: Bu durumda, büyük hizmet değerlerine karşılık gelir df satırları seçmek için df.loc[...] kullanabilirsiniz /github.com/pydata/pandas/issues/8717 – Jeff

İlgili konular