2017-07-18 164 views
4

我是一個begginer,它已經很長一段時間了,我沒有編寫任何代碼:-)我使用請求庫從Incapsula(雲網絡安全服務)API來獲取關於網站的一些統計信息。我最終想要的是將「交通類型,時間戳和編號」寫入文件以創建報告。 API迴應是這樣的:Python - 從數據框提取信息(JSON)

{ 
    "res": 0, 
    "res_message": "OK", 
    "visits_timeseries" : [ 
     { 
      "id":"api.stats.visits_timeseries.human", 
      "name":"Human visits", 
      "data":[ 
       [1344247200000,50], 
       [1344247500000,40], 
       ... 
      ] 
     }, 
     { 
      "id":"api.stats.visits_timeseries.bot", 
      "name":"Bot visits", 
      "data":[ 
       [1344247200000,10], 
       [1344247500000,20], 
       ... 
      ] 
     } 

我恢復Visit_timeseries數據是這樣的:

r = requests.post('https://my.incapsula.com/api/stats/v1', params=payload) 
reply=r.json() 
reply = reply['visits_timeseries'] 
reply = pandas.DataFrame(reply) 

我以這樣的形式恢復數據(在UNIX時間日期,數量訪問):

print(reply[['name', 'data']].head()) 

name            data 
0 Human visits [[1500163200000, 39], [1499904000000, 73], [14... 
1 Bot visits [[1500163200000, 1891], [1499904000000, 1926],... 

我不知道如何從數據框中提取我想要的字段,以便只將它們寫入到excel中。我需要將數據字段修改爲兩行(日期,值)。並且只將名稱作爲頂行。

什麼是偉大的是:

 Human Visit  Bot Visit 
Date  Value   Value 
Date  Value   Value 
Date  Value   Value 

感謝您的幫助!

回答

1

好吧,如果這是任何幫助,這是一個硬編碼的版本:

import pandas as pd 

reply = { 
    "res": 0, 
    "res_message": "OK", 
    "visits_timeseries" : [ 
     { 
      "id":"api.stats.visits_timeseries.human", 
      "name":"Human visits", 
      "data":[ 
       [1344247200000,50], 
       [1344247500000,40] 
      ] 
     }, 
     { 
      "id":"api.stats.visits_timeseries.bot", 
      "name":"Bot visits", 
      "data":[ 
       [1344247200000,10], 
       [1344247500000,20] 
      ] 
     } 
     ] 
     } 

human_data = reply['visits_timeseries'][0]['data'] 
bot_data = reply['visits_timeseries'][1]['data'] 

df_h = pd.DataFrame(human_data, columns=['Date', 'Human Visit']) 
df_b = pd.DataFrame(bot_data, columns=['Date', 'Bot Visit']) 
df = df_h.append(df_b, ignore_index=True).fillna(0) 
df = df.groupby('Date').sum()