python Dataframe pandas 将数据分割成时间跨度相等的数据块

先上数据,有如下dataframe格式的数据,列名分别为date、ip,我需要统计每5s内出现的ip,以及这些ip出现的频数。

        ip                  date
0   127.0.0.21  15/Jul/2017:18:22:16
1   127.0.0.13  15/Jul/2017:18:22:16
2   127.0.0.11  15/Jul/2017:18:22:17
3   127.0.0.11  15/Jul/2017:18:22:20
4   127.0.0.21  15/Jul/2017:18:22:21
5   127.0.0.13  15/Jul/2017:18:22:22
6   127.0.0.14  15/Jul/2017:18:26:36
7   127.0.0.16  15/Jul/2017:18:32:15
8   127.0.0.11  15/Jul/2017:18:36:03

在网上找了很久但是没看到python的相关答案,但在stackoverflow找到了R语言的解法,有兴趣可以看看
受它的启发,我用不太优雅的方式实现了我的需求,有更好解决方法的请不吝赐教:

step1: 将数据中日期格式变为标准格式

#date_ip为我的dataframe数据
date_ip['date'] = pd.to_datetime(date_ip['date'], format='%d/%b/%Y:%H:%M:%S')

step2: 将数据的开始时间、结束时间,按5s分割(由于时间段可能不是恰好是5s的倍数,为避免最后一个时间丢失,因此在最后加上5s)

frequency = 5
time_range = pd.date_range(date_ip['date'][0], date_ip['date'][date_ip.shape[0]-1]+frequency*Second(), freq='%sS'%frequency)

step3: 将date变为索引

date_ip = date_ip.set_index('date')

step4: 对每个时间段内的数据进行频数计算(由于通过标签切片时会包含头、尾数据,为避免重复计算,因此在尾部减1s)

for i in xrange(0,len(time_range)-1):
    print get_frequency(date_ip.loc[time_range[i]:time_range[i+1]-1*Second()])

完整的代码

import pandas as pd
from pandas.tseries.offsets import Second
def get_frequency(date_ip):
    ip_frequency = {}
    for i in xrange(0,date_ip.shape[0]):
        ip_frequency[date_ip['ip'][i]] = ip_frequency.get(date_ip['ip'][i], 0) + 1
    return ip_frequency,date_ip.shape[0]

if __name__ == '__main__': 
    date_ip['date'] = pd.to_datetime(date_ip['date'], format='%d/%b/%Y:%H:%M:%S')

    frequency = 5
    time_range = pd.date_range(date_ip['date'][0], date_ip['date'][date_ip.shape[0]-1]+frequency*Second(), freq='%sS'%frequency)  
    date_ip = date_ip.set_index('date')
    for i in xrange(0, len(time_range) - 1):
        print get_frequency(date_ip.loc[time_range[i]:time_range[i + 1]-1*Second()])

文章开头数据运行结果:

({'127.0.0.21' : 1, '127.0.0.13' : 1, '127.0.0.11' : 2}, 4)
({'127.0.0.21': 1, '127.0.0.13': 1}, 2)
({'127.0.0.14': 1}, 1)
({'127.0.0.16': 1}, 1)
({'127.0.0.11': 1}, 1)
  • 5
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值