Pandas,分组查找最大值,返回值和计数
我有一个包含日志数据的pandas数据框:
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
我想找出每个主机上错误最多的服务:
host service no
0 this.com mail 2
1 that.com mail 1
2 other.net web 2
我找到的唯一解决办法是按主机和服务进行分组,然后遍历索引的第0层。
有没有人能建议一个更好、更简短的方法?不需要遍历?
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
完整代码可以在这里找到:https://gist.github.com/bjelline/d8066de66e305887b714
1 个回答
4
给定一个叫做 df
的数据框,下一步是根据 host
这个值进行分组,然后用 idxmax
来聚合数据。这样做的目的是找出每组中服务值最大的那一行的索引。接着,你可以使用 df.loc[...]
来选择 df
中对应于最大服务值的行:
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