将groupby的结果合并到pandas中的原始数据帧中

2024-05-23 17:52:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下411165行的熊猫数据帧:

    LastTime        Dur         SrcAddr     DstAddr    Proto Sport  Dport
0   03:20:18.581977 0.816447    10.0.0.1    10.0.0.4    udp 57532   tftp
1   03:20:32.313861 4.885413    10.0.0.2    10.0.0.4    udp 59977   tftp
2   03:20:37.366970 4.938308    10.0.0.2    10.0.0.4    udp 59977   tftp
3   03:20:42.420143 4.938177    10.0.0.2    10.0.0.4    udp 59977   tftp
4   03:20:47.473281 4.938372    10.0.0.2    10.0.0.4    udp 59977   http-alt
... ... ... ... ... ... ... ...
411161  22:28:29.841361 0.000000    231.127.193.147 10.0.0.4    udp 37335   tftp
411162  22:28:29.933401 0.000000    39.216.12.51    10.0.0.4    udp 36823   tftp
411163  22:28:29.997108 0.000000    153.183.248.241 10.0.0.4    udp 37336   tftp
411164  22:28:30.148128 0.000000    49.29.36.35 10.0.0.4    udp 36824   tftp
411165  22:28:30.229133 0.000000    62.248.30.126   10.0.0.4    udp 37337   tftp

我对数据帧执行了分组操作,以100:

grouper=dataset.groupby([(np.arange(len(dataset.index))//100),'DstAddr','Dport'])
ct_sv_dst=grouper['LastTime'].count()

groupby操作的结果是:

DstAddr   Dport   
0     10.0.0.3  http-alt      2
      10.0.0.4  tftp         98
1     10.0.0.3  http-alt     33
      10.0.0.4  tftp         67
2     10.0.0.3  http-alt     34
                           ... 
4107  10.0.0.4  tftp        100
4108  10.0.0.4  tftp        100
4109  10.0.0.4  tftp        100
4110  10.0.0.4  tftp        100
4111  10.0.0.4  tftp         66
Name: LastTime, Length: 6252, dtype: int64

现在我想将分组操作的结果合并到原始数据帧中,请有人指导我如何实现这一点。 我想要的结果如下:

      LastTime      Dur         SrcAddr     DstAddr    Proto Sport  Dport gc
0   03:20:18.581977 0.816447    10.0.0.1    10.0.0.4    udp 57532   tftp  98
1   03:20:32.313861 4.885413    10.0.0.2    10.0.0.4    udp 59977   tftp  98
2   03:20:37.366970 4.938308    10.0.0.2    10.0.0.4    udp 59977   tftp  98
3   03:20:42.420143 4.938177    10.0.0.2    10.0.0.4    udp 59977   tftp  98
4   03:20:47.473281 4.938372    10.0.0.2    10.0.0.4    tcp 59977  http-alt 2
.
.
100  02:20          3.232       10.0.0.1    10.0.0.3    tcp 3234  http-alt 33 
101  02:20          3.232       10.0.0.1    10.0.0.4    udp 3234  tftp    67   

Tags: 数据httpaltdatasetprotoudptftpgroupby
2条回答

在连接之前,需要确保两个数据帧具有相同的列。到目前为止,groupby操作的结果缺少几列。通过向ct_sv_dst = grouper.agg({'LastTime':'count', 'proto':lambda x: x.value_counts().index[0], MORE AGG RULES HERE})传递更多列分组规则来修复此问题

然后用pd.dataframe.concat()连接原始数据帧和groupby()agg()的结果。更多详情here

这就行了

dataset['gc'] = grouper['LastTime'].transform('count')

相关问题 更多 >