Converting a Pandas dataframe to JSON format: {name of column1: [corresponding values], name of column2: [corresponding values], name

I'm a beginner in Python and pandas. I've been attempting to convert a pandas dataframe into JSON with the following format:

{column1 name : [Values], column2 name: [values], Column3 name... }

I have tried using this code:

df.to_json(orient='columns')

However, it gives me the following output:

{"Col1 name":{"row key1": value1, "row key2": value2}, "Col2 name":{"row key1": value1, "row key2": value2}}

If someone could provide assistance or suggest an alternative method for converting the dataframe without including the row keys, I would greatly appreciate it.

For reference, my dataframe looks like this:

      date       batch          result            LSL            USL    target
0    2010-01-16  00154354A0     1100.0           680.0          1210.0  1100.0
1    2010-01-16  00164354A2     1070.0           680.0          1210.0  1100.0

The desired resulting format is:

{'date':['2010-01-16', '2010-01-16'], 'batch': ['00154354A0', '00164354A2'], 'result':[1100.0, 1070.0], 'LSL':...}

Thank you very much in advance.

Answer №1

Give this a try:

In [2019]: df.to_dict(orient='list')
Out[2019]: 
{'date': ['2020-01-21', '2020-02-18'],
 'batch': ['00152340B5', '00162340C7'],
 'result': [1050.0, 1068.0],
 'LSL': [670.0, 682.0],
 'USL': [1200.0, 1220.0],
 'target': [1050.0, 1050.0]}

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

Deducing characteristics of Azure virtual machines from text with Python Software Development Kit

Looking to automatically determine the available memory and number of vCPUs based on an Azure VM size provided as a string (e.g. "STANDARD_A4_v2"). I've searched through azure-mgmt-compute without success. I came across this post which uses a Compute ...

What is the best way to turn off console messages from pywebkit?

One common issue that often arises is how to prevent the following messages from displaying on the terminal: ** Message: console message: @1: Refused to set unsafe header "cookie" ** Message: console message: @1: Refused to set unsafe header ...

Exploring the automated retrieval of data from arrays in Java objects: A comprehensive guide

My goal is to automatically create Java objects from JSON data obtained from a REST API. The JSON array contains properties of different shops, and I aim to generate one object per shop with all its respective properties. The following code helped me achi ...

Verifying user identity in Django Rest Framework by integrating with Google Authentication

When implementing JWT authentication using username/password, the process goes as follows: from rest_framework_simplejwt.serializers import TokenObtainPairSerializer '''The POST request appears like this: <QueryDict: { 'csrfmid ...

What is causing json_decode to not work on this specific json object?

I've been working on a PHP script that receives a JSON object from http://www.reddit.com/search.json via an HTTP GET request. After some testing, I can confirm that the script successfully retrieves the JSON object. However, when I try to use json_dec ...

Transmitting JSON data to Slack through an HTTP POST submission

I am encountering an issue while attempting to send a message through Slack's chat.postMessage API call. I can successfully encode my test messages in HTTP GET, but I am struggling with achieving the same outcome using JSON in an HTTP POST request. I ...

How can you give a block a unique name using a variable in Jinja2?

In the template "base.html" that I have, there is a set of ids called list_of_ids. The template contains a for loop that goes through each id in this list and outputs a specific block of content for each one. {% set list_of_ids = ['id1', 'i ...

Python - incorrect number of arguments provided for f.write: expected 1 argument, but received

import os from os import stat from pwd import getpwuid searchFolder = raw_input("Please input the directory you want to search (e.g. /Users/bubble/Desktop/): ") resultsTxtLocation = raw_input("FIBS will save the results in a txt file. Where should we save ...

Using Python to delete chunks of text

Within my Python program, I am attempting to eliminate sizable chunks of text from a file. These blocks of text always start with /translation="SOMETEXT" And conclude with the second quote mark. If anyone has any guidance on how I can achieve this task, ...

utilize ajax success method to extract json data

I'm currently working on displaying and parsing JSON data in the success function of an AJAX call. This is what I have so far: AJAX: data = "Title=" + $("#Title").val() + "&geography=" + $("#geography").val(); alert(data); url= "/portal/getRe ...

Extract an array segment from a JSON document and convert it into a list

In my JSON file, there is a valid list/Array of databases structured as follows: { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug" } }, "settings": { ...

error in kv file due to incorrect id declaration

I came across a helpful tutorial on Kivy Design Language that I would like to follow: Kivy Design Language Tutorial. Following the instructions provided in the tutorial, I have written the following code along with its corresponding .kv file: import kivy f ...

"Utilizing PHP MySQL queries to generate an array and encode it into JSON format for

Below is the code snippet that I am having trouble with: $objDbResultByModel = $objDatabase->Query($modelQuery); $return_arr = array(); echo "<h3>Total Model No<br></h3><strong>"; while ($mixRow = $objDbResultByModel->FetchAr ...

Display the DOM following Selenium driver.get call

When working with requests, I usually just print the response after making a GET request. However, I sometimes find it challenging to determine if certain parts of the page are included in the response, especially when the website utilizes React or jQuery. ...

Decode JSON data in PHP for Joomla via the json_decode function

Looking for some assistance with decoding a JSON file in my database. Here is the data: {"img":["images/logo2.png","images/logo.png"]} I am trying to display the images like this: images/logo2.png images/logo.png ...

Python Google API client: Issues with log level and debug level functionality not functioning as expected

During the creation of a simple Python app on AppEngine, I came across this helpful page: https://developers.google.com/api-client-library/python/guide/logging The page suggests using the following code to set the log level: import logging logger = logg ...

Is there a way to utilize JSON.NET to deserialize a collection of JSON objects into an array?

The terms "array" and "objects" might not be exact, but you catch my drift. Looking at the sample for serializing/deserializing a custom object from the official documentation: product.Name = "Apple"; product.ExpiryDate = new DateTime(2008, 12, 28); p ...

What is the best way to make a python script repeat a set number of times continuously?

To repeat a Python script 10 times, I encountered an intentional error that halts the process. This occurs because the script interacts with a website where a random number of questions are generated, up to a maximum of 7. To handle this variability and pr ...

Transform the JSON output from a REST API into a table format for integration into Power BI

After transforming the JSON output into a table in Power BI, I encountered a challenge. https://i.stack.imgur.com/UvOHq.png Despite my efforts, I couldn't figure out how to convert the above format into the desired one in Power BI. If anyone has su ...

Creating dynamic JSON endpoints using JSP with Spring MVC

When working with JSON in my webapp, I have successfully passed a variable wordId to the Spring-mvc Controller using a static URL. However, I am unsure of the best practice for dealing with dynamic or parametric URLs. Controller Section: @RequestMapping( ...