如何按列值的计数进行分组并对其进行排序?

Hav*_*Shi 2 python sorting group-by count pandas

如何按列值的计数进行分组并对其进行排序?

我是熊猫学习者。

我有名为 data.log 的原始数据框。现在我想计算按“c-ip-1”分组的数字,并对结果进行排序。

原始数据.log:

   sc-status  sc-substatus  sc-win32-status  time-taken       c-ip-1
0        200             0                0         986  31.7.188.55
1        200             0                0        2539  31.7.188.55
2        200             0                0        1172  31.7.188.56
3        200             0                0        3152  31.7.188.80
4        200             0                0        1091  31.7.188.80
...
99       200             0                0        1115  31.9.200.60
100      200             0                0        2000  31.9.200.61
Run Code Online (Sandbox Code Playgroud)

预期结果如下:

         c-ip-1                 count
0        31.7.188.56            1     
1        31.9.200.61            1  
2        31.7.188.55            2  
...
34       31.9.200.60            5
Run Code Online (Sandbox Code Playgroud)

我尝试编写Python代码并运行它,但失败了:

import pandas as pd

df = pd.read_table('data.log', sep=" ")

print(df[['c-ip-1']].groupby(['c-ip-1']).agg(['count'])
Run Code Online (Sandbox Code Playgroud)

我该如何使用python解决这个问题?

jez*_*ael 5

我认为你需要聚合 by GroupBy.size、 thenSeries.sort_values和 last Series.reset_index

#better is more general separator `\s+` - one or more whitespaces
df = pd.read_table('data.log', sep="\s+")

df1 = df.groupby('c-ip-1').size().sort_values().reset_index(name='count')
print (df1)
        c-ip-1  count
0  31.7.188.56      1
1  31.9.200.60      1
2  31.9.200.61      1
3  31.7.188.55      2
4  31.7.188.80      2
Run Code Online (Sandbox Code Playgroud)

大熊猫的大小和数量有什么区别?