Python - How to open a JSON file in pandas and convert it into DataFrame?

Learn, how can we open a JSON file in pandas and convert it into DataFrame?
Submitted by Pranit Sharma, on August 30, 2022

Pandas is a special tool that allows us to perform complex manipulations of data effectively and efficiently. Inside pandas, we mostly deal with a dataset in the form of DataFrame. DataFrames are 2-dimensional data structures in pandas. DataFrames consist of rows, columns, and data.

What is a JSON file?

A JSON file is just like a Python dictionary which holds the elements in the form of a key:value pair. JSON allows programmers to store different data types in the form of human-readable code, with the keys representing the names and the values containing the related data to it.

Opening a JSON file in pandas and convert it into DataFrame

In pandas, we have a method called pandas.read_json() which is used when we want to import a JSON file in Pandas. To import a JSON file into pandas and convert it into a DataFrame, we must have a JSON file on our local machine.

After downloading the JSON file, we will open it in Pandas with pandas.read_json() method, and then we will convert it into DataFrame with the help of pandas.DataFrame() method.

Let us understand with the help of an example,

Python program to open a JSON file in pandas and convert it into DataFrame

# Importing pandas package
import pandas as pd

# Importing a json file
d = pd.read_json('E:/sample1.json', typ='series')

# Display the json file
print("Imported JSON file:\n",d,"\n")

# Creating DataFrame
df=pd.DataFrame(d)

# Display the DataFrame
print("Original DataFrame:\n",df,"\n\n")

Output

The output of the above program is:

Example: Open a JSON file in pandas and convert it into DataFrame

Python Pandas Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.