![](/img/trans.png)
[英]Faster method to extract information from complex nested json in python dataframe
[英]Python - Extract information from dataframe (JSON)
我是一個初學者,很長一段時間以來我什么都沒編碼:-)我正在使用請求庫從Incapsula(Cloud Web Security Service)API檢索JSON數據以獲取有關網站的一些統計信息。 我最后想要的是將“流量類型,時間戳和數字”寫入文件以創建報告。 API響應是這樣的:
{
"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
謝謝你的幫助!
好吧,如果有幫助,這是一個硬編碼版本:
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.