The Wayback Machine - https://web.archive.org/web/20241004075438/https://www.geeksforgeeks.org/pandas-convert-json-to-dataframe/
Open In App

Pandas Convert JSON to DataFrame

Last Updated : 11 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

When working with data, it’s common to encounter JSON (JavaScript Object Notation) files, which are widely used for storing and exchanging data. Pandas, a powerful data manipulation library in Python, provides a convenient way to convert JSON data into a Pandas data frame. In this article, we’ll explore how to convert JSON data into a Pandas DataFrame, covering various scenarios and options you might encounter along the way.

What is a JSON file?

JSON stands for Java script object notation. It stores the data in the format of a key-value pair . We can read the data from the various file formats such as CSV, JSON and Excel. The pandas library is used to work with the data frames and manipulate the data frames. we can read data from various files with the help of pandas .

  • Importing the pandas Library.
  • Reading the JSON file.
  • Converting into data frame .
  • Printing the data frame.

Pandas Convert JSON to DataFrame

Importing the pandas

This is the first step to working with the data frames in Pandas. First, we import Panda’s library from Python. To convert a file to the data frame, we need to have a JSON file to perform that operation. First, we will create a JSON file or we will just download a Json file.

For importing the pandas library in python we need to use the import statement:

Python
import pandas as pd 

Using json Module to create a file

Here, we will create a sample json file here the json file is as shown below .

Python
import json

data = {
    "Name": {
        "0": "Harsha",
        "1": "Vardhan",
        "2": "Krishna",
        "3": "Hanuman",
        "4": "Shiva"
    },
    "Roll_no": {
        "0": 1,
        "1": 2,
        "2": 3,
        "3": 4,
        "4": 5
    },
    "subject": {
        "0": "C",
        "1": "JAVA",
        "2": "C++",
        "3": "SWIFT",
        "4": "PYTHON"
    }
}

with open('subject.json', 'w') as json_file:
    json.dump(data, json_file, indent=4)
  • In the above code we have created a json file and the json file consists of key value pair.
  • The data is stored in the form of strings as a keys and values as a list .
  • We will read the json file with the help of the read_json() to read the contents of the file .

Converting into DataFrame :

Python
#Importing the pandas Library 
import pandas as pd 
#Reading the JSON File 
dataFrame = pd.read_json("subject.json")
#Printing the data Frame
print(dataFrame)

Output :

        Name      Roll_no   subject 
0 Harsha 1 C
1 Vardhan 2 JAVA
2 Krishna 3 C++
3 Hanuman 4 SWIFT
4 Shiva 5 PYTHON

Now, we will implement the same on a downloaded dataset,

Conclusion :

As mentioned in the above way we can read the data from the JSON File from the Pandas and we can convert the JSON File into the DataFrame in the DataFrame .

Pandas Convert JSON to DataFrame – FAQs

How to Convert JSON Data to Python Data?

To convert JSON data into Python data structures, you can use Python’s built-in json module. This conversion is straightforward, turning JSON into native Python dictionaries, lists, etc.:

import json

# Example JSON data as string
json_data = '{"name": "John", "age": 30, "city": "New York"}'

# Convert JSON to Python
python_data = json.loads(json_data)
print(python_data) # Outputs: {'name': 'John', 'age': 30, 'city': 'New York'}

How to Read JSON into Pandas?

To read JSON data into a pandas DataFrame, use the read_json() method. This is useful for handling JSON data directly from files or JSON strings:

import pandas as pd

# Assuming json_data is a JSON string
df = pd.read_json(json_data)
print(df)

If you have a file containing JSON data, you can read it directly:

# Load JSON data from a file
df = pd.read_json('path_to_file.json')
print(df)

How to Convert DataFrame to JSON in Python?

To convert a pandas DataFrame into a JSON format, use the to_json() method. This method is versatile and allows you to specify the format of the JSON output:

df = pd.DataFrame({
'name': ['John', 'Jane'],
'age': [30, 25],
'city': ['New York', 'Los Angeles']
})

# Convert DataFrame to JSON
json_output = df.to_json(orient='records')
print(json_output)

How to Save a JSON File Using Pandas?

To save a DataFrame as a JSON file using pandas, use the to_json() method with a file path:

# Save DataFrame to a JSON file
df.to_json('output_file.json', orient='records')

How to Convert JSON to CSV in DataFrame?

To convert JSON data to a CSV file using pandas, first read the JSON into a DataFrame and then use the to_csv() method to save it as CSV:

# Load JSON into DataFrame
df = pd.read_json(json_data)

# Save DataFrame to CSV
df.to_csv('output_file.csv', index=False)


Similar Reads

How to convert pandas DataFrame into JSON in Python?
Data Analysis is an extremely important tool in today's world. A key aspect of Data Analytics is an organized representation of data. There are numerous data structures in computer science to achieve this task. In this article, we talk about two such data structures viz. Pandas DataFrame and JSON. Further, we see how to convert DataFrames to JSON f
4 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Load JSON String into Pandas DataFrame
Let us see how can we use a dataset in JSON format in our Pandas DataFrame. This can be done using the built-in read_json() function. It enables us to read the JSON in a Pandas DataFrame. Example : Consider the JSON file path_to_json.json : # importing the module import pandas # reading the file data = df.read_json("path_to_json.json") #
1 min read
Exporting Pandas DataFrame to JSON File
Let us see how to export a Pandas DataFrame as a JSON file. To perform this task we will be using the DataFrame.to_json() and the pandas.read_json() function. Example 1 : C/C++ Code # importing the module import pandas as pd # creating a DataFrame df = pd.DataFrame([['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']], index =['row 1', 'row 2', 'row3
2 min read
Normalizing Nested Json Object Into Pandas Dataframe
The encapsulation of one or more JSON objects into another JSON object is called a nested JSON object. There are various circumstances when we have the data in JSON object form and have to imply numerous functions on the dataset. In such cases, we can use the Python library called Pandas which is used for datasets. For converting into a Pandas data
3 min read
Python Pandas Dataframe To Nested Json
When working with data in Python,Pandas is a popular library for handling tabular data efficiently. Converting a Pandas DataFrame to a nested JSON structure can be necessary for various reasons, such as preparing data for API responses or interacting with nested JSON-based data structures. In this article, we will explore four approaches to achievi
3 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
How to Convert Integer to Datetime in Pandas DataFrame?
Let's discuss how to convert an Integer to Datetime in it. Now to convert Integers to Datetime in Pandas DataFrame. Syntax of pd.to_datetimedf['DataFrame Column'] = pd.to_datetime(df['DataFrame Column'], format=specify your format)Create the DataFrame to Convert Integer to Datetime in Pandas Check data type for the 'Dates' column is Integer. Python
2 min read
How to Convert Dataframe column into an index in Python-Pandas?
Pandas provide a convenient way to handle data and its transformation. Let's see how can we convert a data frame column to row name or index in Pandas. Create a dataframe first with dict of lists. C/C++ Code # importing pandas as pd import pandas as pd # Creating a dict of lists data = {'Name':["Akash", "Geeku", "Pankaj
2 min read
How to Convert Index to Column in Pandas Dataframe?
Pandas is a powerful tool which is used for data analysis and is built on top of the python library. The Pandas library enables users to create and manipulate dataframes (Tables of data) and time series effectively and efficiently. These dataframes can be used for training and testing machine learning models and Analyzing data. Converting Index to
2 min read
How to Convert String to Integer in Pandas DataFrame?
Let's see methods to convert string to an integer in Pandas DataFrame: Method 1: Use of Series.astype() method. Syntax: Series.astype(dtype, copy=True, errors=’raise’) Parameters: This method will take following parameters: dtype: Data type to convert the series into. (for example str, float, int).copy: Makes a copy of dataframe/series.errors: Erro
3 min read
How to Convert Integers to Strings in Pandas DataFrame?
In this article, we'll look at different methods to convert an integer into a string in a Pandas dataframe. In Pandas, there are different functions that we can use to achieve this task : map(str)astype(str)apply(str)applymap(str) Example 1 : In this example, we'll convert each value of a column of integers to string using the map(str) function. C/
3 min read
Fastest way to Convert Integers to Strings in Pandas DataFrame
Pandas - An open-source library which is used by any programmer. It is a useful library that is used for analyzing the data and for manipulating the data. It is fast, flexible, and understandable, handles the missing data easily. Not only it provides but also enhances the performance of data manipulation and analysis tools with the powerful data st
2 min read
How to convert index in a column of the Pandas dataframe?
Each row in a dataframe (i.e level=0) has an index value i.e value from 0 to n-1 index location and there are many ways to convert these index values into a column in a pandas dataframe. First, let's create a Pandas dataframe. Here, we will create a Pandas dataframe regarding student's marks in a particular subject with columns roll number, name, s
4 min read
Convert a series of date strings to a time series in Pandas Dataframe
During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. pandas.to_datetime() Function helps in converting a date string to a python date object. So, it can be utilized
3 min read
How to Convert Integers to Floats in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, etc. There are 2 methods to convert Integers to Floats: Method 1: Using DataFrame.astype() method Syntax : DataFrame.astype(dtype, copy=True, errors=’raise’, **kwargs) Example 1: Conve
4 min read
How to Convert Floats to Strings in Pandas DataFrame?
In this post, we'll see different ways to Convert Floats to Strings in Pandas Dataframe? Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to String, String to Integer, Float to String, etc. There are three methods to convert Float to String: Method 1: Using DataF
4 min read
How to Convert Float to Datetime in Pandas DataFrame?
Pandas Dataframe provides the freedom to change the data type of column values. We can change them from Integers to Float type, Integer to Datetime, String to Integer, Float to Datetime, etc. For converting float to DateTime we use pandas.to_datetime() function and following syntax is used : Syntax: pandas.to_datetime(arg, errors=’raise’, dayfirst=
3 min read