2016-11-07 64 views
1

我有AWS EC2實例CPU利用率,給我在CSV格式類似這樣的其他指標數據:團聚體的時間序列數據

Date,Time,CPU_Utilization,Unit 
2016-10-17,09:25:00,22.5,Percent 
2016-10-17,09:30:00,6.534,Percent 
2016-10-17,09:35:00,19.256,Percent 
2016-10-17,09:40:00,43.032,Percent 
2016-10-17,09:45:00,58.954,Percent 
2016-10-17,09:50:00,56.628,Percent 
2016-10-17,09:55:00,25.866,Percent 
2016-10-17,10:00:00,17.742,Percent 
2016-10-17,10:05:00,34.22,Percent 
2016-10-17,10:10:00,26.07,Percent 
2016-10-17,10:15:00,20.066,Percent 
2016-10-17,10:20:00,15.466,Percent 
2016-10-17,10:25:00,16.2,Percent 
2016-10-17,10:30:00,14.27,Percent 
2016-10-17,10:35:00,5.666,Percent 
2016-10-17,10:40:00,4.534,Percent 
2016-10-17,10:45:00,4.6,Percent 
2016-10-17,10:50:00,4.266,Percent 
2016-10-17,10:55:00,4.2,Percent 
2016-10-17,11:00:00,4.334,Percent 
2016-10-17,11:05:00,4.334,Percent 
2016-10-17,11:10:00,4.532,Percent 
2016-10-17,11:15:00,4.266,Percent 
2016-10-17,11:20:00,4.266,Percent 
2016-10-17,11:25:00,4.334,Percent 

正如顯而易見的,這是每5分鐘的報道。我無法訪問aws-cli。我需要對此進行處理並每15分鐘報告一次平均利用率以便可視化。也就是說,對於每個小時,我都需要在前15分鐘,接下來的15分鐘等內找到這些值的平均值。所以,我會每小時報告4個值。

樣品輸出將是:

Date,Time,CPU_Utilization,Unit 
2016-10-17,09:30:00,14.517,Percent 
2016-10-17,09:45:00,40.414,Percent 
2016-10-17,10:00:00,33.412,Percent 
2016-10-17,10:15:00,26.785,Percent 
... 

一種方式做到這一點。將讀取整個文件(其10000+)線,那麼對於每個日期,發現屬於一個窗口中的值15分鐘,計算它們的平均值並重復所有的值。這似乎不是最好的和最有效的方法。有沒有更好的方法來做到這一點?謝謝。

+0

該文件是否真的太大而無法完全讀取? 10000行聽起來不夠大,無法在'numpy'數組中讀取並在那裏處理。我想這實際上應該比循環遍歷文件和逐行讀取更好。 – jotasi

+0

@jotasi不,它並不大。即使我考慮將整個文件作爲Numpy數組讀取的方法。我將如何繼續?我應該讀取屬於特定日期的行嗎?任何幫助,將不勝感激。 – theironhide

+0

熊貓是做這種事情。 –

回答

1

由於您的輸入數據實際上很小,我建議使用np.genfromtxt一次性讀取它。然後,您可以通過檢查何時達到完整的四分之一小時來找到適當的範圍,並通過計算剩下多少整個四分之一來結束。然後你可以使用np.reshape來獲取數組的形式數小時季度的行,然後平均超過那些行:

import numpy as np 

# Read in the data: 
data = np.genfromtxt("data.dat", skip_header=1, 
        dtype=[("date", "|S10"), 
          ("time", "|S8"), 
          ("cpu_usage", "f8")], 
        delimiter=',', usecols=(0, 1, 2)) 

# Find the first full quarter: 
firstQuarterHour = 0 
while not (int(data[firstQuarterHour]["time"][3:5]) % 15 == 0): 
    firstQuarterHour += 1 
noOfQuarterHours = data[firstQuarterHour:].shape[0]/3 

# Create a reshaped array 
reshaped = data[firstQuarterHour:firstQuarterHour+3*noOfQuarterHours+1].reshape(
    (noOfQuarterHours, 3)) 

# Average over cpu_usage and take the appropriate dates and times: 
cpu_usage = reshaped["cpu_usage"].mean(axis=1) 
dates = reshaped["date"][:, 0] 
times = reshaped["time"][:, 0] 

現在你可以使用這些陣列,例如保存到另一個文本文件通過使用np.savetxt