
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Put Pandas DataFrame into JSON File and Read It Again
To put a Pandas DataFrame into a JSON file and read it again, we can use to_json() and read_json() methods.
Steps
- Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df.
- Print the input DataFrame, df.
- Use to_json() method to dump the DataFrame into a JSON file.
- Use read_json() method to read the JSON file.
Example
import pandas as pd df = pd.DataFrame( { "x": [5, 2, 7, 0], "y": [4, 7, 5, 1], "z": [9, 3, 5, 1] } ) print "Input DataFrame is:\n", df print "JSON output for input DataFrame: ", df.to_json("test.json") print "Reading the created JSON file" print "Dataframe is: \n", pd.read_json("test.json")
Output
Input DataFrame is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1 JSON output for input DataFrame: None Reading the created JSON file Dataframe is: x y z 0 5 4 9 1 2 7 3 2 7 5 5 3 0 1 1
When we use df.to_json("test.json"), it creates a JSON file called "test.json" from the data given in the DataFrame.
Next, when we use pd.read_json("test.json"), it reads the data from test.json.
Advertisements