最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python使用pandas實現(xiàn)數(shù)據(jù)分割實例代碼

 更新時間:2018年01月25日 09:48:36   作者:llwang_10  
這篇文章主要介紹了python使用pandas實現(xiàn)數(shù)據(jù)分割實例代碼,介紹了使用pandas實現(xiàn)對dataframe格式的數(shù)據(jù)分割成時間跨度相等的數(shù)據(jù)塊,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下

本文研究的主要是Python編程通過pandas將數(shù)據(jù)分割成時間跨度相等的數(shù)據(jù)塊的相關(guān)內(nèi)容,具體如下。

先上數(shù)據(jù),有如下dataframe格式的數(shù)據(jù),列名分別為date、ip,我需要統(tǒng)計每5s內(nèi)出現(xiàn)的ip,以及這些ip出現(xiàn)的頻數(shù)。

 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

在網(wǎng)上找了很久但是沒看到python的相關(guān)答案,但在stackoverflow找到了R語言的解法,有興趣可以看看。

受它的啟發(fā),我用不太優(yōu)雅的方式實現(xiàn)了我的需求,有更好解決方法的請不吝賜教:

step1: 將數(shù)據(jù)中日期格式變?yōu)闃?biāo)準(zhǔn)格式

#date_ip為我的dataframe數(shù)據(jù)
date_ip['date'] = pd.to_datetime(date_ip['date'], format='%d/%b/%Y:%H:%M:%S')

step2: 將數(shù)據(jù)的開始時間、結(jié)束時間,按5s分割(由于時間段可能不是恰好是5s的倍數(shù),為避免最后一個時間丟失,因此在最后加上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變?yōu)樗饕?/h2>
date_ip = date_ip.set_index('date')

step4: 對每個時間段內(nèi)的數(shù)據(jù)進(jìn)行頻數(shù)計算(由于通過標(biāo)簽切片時會包含頭、尾數(shù)據(jù),為避免重復(fù)計算,因此在尾部減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()])

文章開頭數(shù)據(jù)運(yùn)行結(jié)果:

({'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)

總結(jié)

以上就是本文關(guān)于python使用pandas實現(xiàn)數(shù)據(jù)分割實例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!

相關(guān)文章

最新評論

兴仁县| 延寿县| 凉山| 双峰县| 屯昌县| 屯门区| 石林| 邯郸市| 黑河市| 罗源县| 济宁市| 珠海市| 临邑县| 黄冈市| 大安市| 子长县| 会泽县| 许昌县| 五原县| 兴义市| 沂南县| 麻江县| 平和县| 太仆寺旗| 开阳县| 溧水县| 荃湾区| 万安县| 承德县| 天门市| 广南县| 金溪县| 永福县| 台北市| 琼中| 阜南县| 雷山县| 会理县| 澄城县| 安平县| 赞皇县|