python使用pandas实现数据分割实例代码

yipeiwu_com7年前Python基础

本文研究的主要是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实现数据分割实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

Python语言生成水仙花数代码示例

Python语言生成水仙花数代码示例

水仙花数是指一个 n 位数 ( n≥3 ),它的每个位上的数字的 n 次幂之和等于它本身。 本文将通过Python代码实现打印水仙花数,具体如下: #水仙花数 #narcissist...

Python+pandas计算数据相关系数的实例

本文主要演示pandas中DataFrame对象corr()方法的用法,该方法用来计算DataFrame对象中所有列之间的相关系数(包括pearson相关系数、Kendall Tau相关...

python使用threading.Condition交替打印两个字符

Python中使用threading.Condition交替打印两个字符的程序。 这个程序涉及到两个线程的的协调问题,两个线程为了能够相互协调运行,必须持有一个共同的状态,通过这个状态来...

Python3 chardet模块查看编码格式的例子

Python3 chardet模块查看编码格式的例子

如下所示: 需要注意的是,如果遇到GBK2312等编码的,在decode和encode时,一律使用GBK进行编码或者解码,这是因为GBK是其他GBK编码的超集,向下兼容所有的GBK编码...

Python查找相似单词的方法

本文实例讲述了Python查找相似单词的方法。分享给大家供大家参考。具体分析如下: 问题: 给你一个单词a,如果通过交换单词中字母的顺序可以得到另外的单词b,那么定义b是a的兄弟单词。现...