Saturday, November 16, 2024
Google search engine
HomeLanguagesExporting Pandas DataFrame to JSON File

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 :

Python3




# 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'],
                  columns =['col 1', 'col 2', 'col3'])
 
# storing the data in JSON format
df.to_json('file.json', orient = 'split', compression = 'infer', index = 'true')
 
# reading the JSON file
df = pd.read_json('file.json', orient ='split', compression = 'infer')
 
# displaying the DataFrame
print(df)


Output : 

We can see that the DataFrame has been exported as a JSON file.

Example 2 :

Python3




# importing the module
import pandas as pd
  
# creating a DataFrame
df = pd.DataFrame(data = [['15135', 'Alex', '25 / 4/2014'],
                   ['23515', 'Bob', '26 / 8/2018'],
                   ['31313', 'Martha', '18 / 1/2019'],
                   ['55665', 'Alen', '5 / 5/2020'],
                   ['63513', 'Maria', '9 / 12 / 2020']],
                  columns =['ID', 'NAME', 'DATE OF JOINING'])
 
# storing data in JSON format
df.to_json('file1.json', orient = 'split', compression = 'infer')
 
# reading the JSON file
df = pd.read_json('file1.json', orient ='split', compression = 'infer')
print(df)


Output : 

We can see that this DataFrame has also been exported as a JSON file.

 

RELATED ARTICLES

Most Popular

Recent Comments