您好,登錄后才能下訂單哦!
怎么在python中使用pandas分割數(shù)據(jù)?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。
具體如下。
先上數(shù)據(jù),有如下dataframe格式的數(shù)據(jù),列名分別為date、ip,我需要統(tǒng)計(jì)每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)雅的方式實(shí)現(xiàn)了我的需求,有更好解決方法的請(qǐng)不吝賜教:
#date_ip為我的dataframe數(shù)據(jù) 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')
step4: 對(duì)每個(gè)時(shí)間段內(nèi)的數(shù)據(jù)進(jìn)行頻數(shù)計(jì)算(由于通過標(biāo)簽切片時(shí)會(huì)包含頭、尾數(shù)據(jù),為避免重復(fù)計(jì)算,因此在尾部減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)
關(guān)于怎么在python中使用pandas分割數(shù)據(jù)問題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。