Python - Retrieve data from a dataframe (JSON)

After taking a break from coding for some time, I am now diving back in as a beginner. I am currently using the requests library to fetch JSON data from the Incapsula API in order to collect stats about website traffic. My goal is to extract and write the "type of traffic, timestamp, and number" to a file for generating reports. The format of the API response looks like this:

{
    "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],
                ...
            ]
        }

I am extracting the Visit_timeseries data using the following method:

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

The extracted data is presented in the form of (date in unix time, number of visits) :

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

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

I'm struggling with extracting specific fields from the dataframe to only include them in the excel file. I need to reformat the 'data' field into two separate rows (date, value), while keeping only the 'name' at the top.

What I envision is :

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

Your assistance with this would be greatly appreciated! Thank you.

Answer №1

If you're looking for a hardcoded solution, here's an example:

import pandas as pd

response =  {
    "code": 0,
    "message": "Success",
    "visits_data" : [
        {
            "id":"api.stats.visits_data.human",
            "name":"Human visits",
            "data":[
                [1344247200000,50],
                [1344247500000,40]
            ]
        },
        {
            "id":"api.stats.visits_data.bot",
            "name":"Bot visits",
            "data":[
                [1344247200000,10],
                [1344247500000,20]
            ]
        }
        ]
        }

human_visits = response['visits_data'][0]['data']
bot_visits = response['visits_data'][1]['data']

df_human = pd.DataFrame(human_visits, columns=['Date', 'Human Visit'])
df_bot = pd.DataFrame(bot_visits, columns=['Date', 'Bot Visit'])
combined_df = df_human.append(df_bot, ignore_index=True).fillna(0)
final_df = combined_df.groupby('Date').sum()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for efficiently webscraping multiple pages with Beautiful Soup

I have been running my web-scraping script for quite some time, but it seems to be stuck on scraping only one URL. I intend to scrape five different URLs, and I am wondering if the issue lies with my loop getting stuck in an infinite loop. Furthermore, I ...

"Unleashing the power of neural networks with the tf.layers.dense and ‎tf.data.Dataset modules in Tensorflow - a

I have two independent variables X1 and X2, and I am looking to predict the dependent variable Y. Training Data X1 X2 Y 11 610 676 52 557 120 78 491 964 77 380 722 24 464 837 86 532 601 99 580 452 10 539 200 88 507 756 How can I achieve this ...

PyCurl is experiencing significant delays in completing its operations

Following the installation of a fresh system on my PC (Windows 10 x64), I am experiencing some challenges with the pycurl lib for python. I tested it on both Python 2.7 and 3.4, but the issue persists regardless of the version. The response time after se ...

function that recursively obtains a list of multiples

Question: Create a recursive function called get_list_of_multiples(numbers, m) that accepts a list of integers and an integer as arguments. This function should return a list of multiples of m from the input list in the same order. If there are no multiple ...

Is there a way to transfer an array of strings and integers from JavaScript to Python 3.8?

I have reviewed similar questions but haven't found a solution that works for me. My inquiry is regarding the following code snippet: function pyInput(){ const buffers = []; proc.stdout.on('data', (chunk) => buffers.push(chunk)) ...

Inquiries Regarding Requests and Beautiful Soup

import requests from bs4 import BeautifulSoup import time import sys url = "https://www.doviz.com/" response = requests.get(url) html_content = response.content soup = BeautifulSoup(html_content,"html.parser") names = soup.find ...

Taking a Symfony approach to handling actions that return a JSON response

Utilizing PHP and CURL, I am retrieving data from a server in one of my actions and then returning the data in JSON format. The code for my action is as follows: public function executeTest(sfWebRequest $request) { $json = $this->getServerResponse ...

Transform Json data into a C# collection

I am encountering an issue while trying to deserialize JSON into a collection of C# objects. The error message I am receiving is as follows: {"Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'Sys ...

What is the best way to align the variables in this JavaScript file with the variables in Flask/Python?

I have a JavaScript file that enables dynamic drop-down menus (i.e. selecting one option affects the others). However, I hard-coded the starting variables in this file to HTML elements 'inverter_oem' and 'inverter_model_name'. Now, I ne ...

jquery struggles to understand jsonp data during cross-domain heartbeats

I have embedded my module, which is an asp.net project, within a "portal". The portal creates an iframe that points to my URL. I understand that this setup may not be ideal, but it was not something I could control. To prevent the session on the main "po ...

What is the proper way to structure a URL in JSON output?

When utilizing JSON output in my project, I encountered the following result: {"short_url":"http:\/\/urlhere\/fb\/37xzk"} However, the desired output should be formatted as follows: { "short_url":"http: //urlhere/fb/37xzk" } ...

Unable to access IP address with Python's httplib module

For some reason, I am unable to establish a connection with any device on my network using the host's IP address. What baffles me is that I can access the same devices through a browser and successfully ping the host without any issues. Below is the c ...

The uncertain nature of data cardinality in Keras model predictions involving various time series and vector inputs causes confusion

My model takes in two inputs - a sequence of vectors and a simple vector, producing a simple vector as an output. For example: x1.shape: (50000,50,2) x2.shape: (50000,2) y.shape: (50000,2) The training and evaluation of my model using model.fit and model. ...

Obtain JSON array by utilizing the Simple Json Library

Here is a glimpse of my JSON data structure. {"Users":[ {"Username":"Admin1", "Password":"123"}, {"Username":"Admin2", "Password":"456"}, {"Username":"Admin3", "Password":"789"} ]} I'm attempting to retrieve all the usernames and passwor ...

TensorFlow: Creating a convolutional autoencoder using subclassing

While experimenting with Keras samples and defining models using subclassing, I encountered some difficulty getting it to work. from keras import layers, Model from keras.datasets import mnist from keras.callbacks import TensorBoard import numpy as np impo ...

Looking to set up a web service that can handle incoming posts, but unsure about the best way to send a response back to jQuery

Good morning, I have a Go code that processes a JSON post request and performs certain actions. However, I am looking to send back either the result or a message to jQuery. package main import ( "fmt" "log" "net/http" "encoding/json" ...

Retrieve data from a JSON array using either JavaScript or PHP

Check out my code snippet: const newData = [{"new_id":"1","new_no":"1","total":"N.A"},{"new_id":"2","new_no":"3","total":"4"},{"new_id":"2","new_no":"4","total":"5"}]; Now, I need to extract specific details from this JSON data based on the 'new_no& ...

How is it possible that my code is continuing to run when it is supposed to be

My API has a limitation of 50 requests per minute for any endpoint. In the code snippet below, I filter objects called orders based on their URLs and store the ones that return data in successfulResponses within my app.component.ts. Promise.all( orders.ma ...

Customizing the date format for each IService in ServiceStack, rather than applying it globally

In my content management system, I have decided not to use the native .NET (WCF) date formatting that is preferred. Instead, in my custom IService, I have set: JsConfig.DateHandler = DateHandler.ISO8601;" However, this decision appears to have caused the ...

Check if a specific index in a Tkinter text widget contains a specific tag

I am looking to enhance my program by checking if an index in a Text widget has a tag attached to it. If a tag is present, I want the program to insert a different character based on that tag. This issue arose from my previous question which can be found h ...