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 :
# 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' ) # readind the JSON file df = pd.read_json( 'file.json' , orient = 'split' , compression = 'infer' ) # displaying the DataFrame print (df) |
chevron_right
filter_none
Output :
We can see that the DataFrame has been exported as a JSON file.
Example 2 :
# 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) |
chevron_right
filter_none
Output :
We can see that this DataFrame has also been exported as a JSON file.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.