温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在python中使用pandas分割数据

发布时间:2021-03-29 17:08:19 来源:亿速云 阅读:531 作者:Leah 栏目:开发技术

怎么在python中使用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)

关于怎么在python中使用pandas分割数据问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI