[PYTHON] [Pandas] Save DataFrame as JSON, load JSON as DataFrame

Since the calculation of the solution in the three-body problem is often completed in advance and saved, the best method at the moment is recorded. As a concrete flow, create data on Python (cycle, state, system name, etc.) → create pandas.DataFrame → save DataFrame as JSON, and then read JSON as DataFrame.

Export DataFrame as JSON

First, prepare a DataFrame image.png To save this as JSON

path = "/data_storage/my_data.json"
dataframe.to_json(path, orient="index", indent="4", double_precision=15)

First, enter the save destination, file name, and extension (.json, of course) in path. As for the options, orient =" index " is used to save each series, and indend =" 4 " is used to start a new line in the JSON file for each series. The result looks like this

{
    "0":{
        "mu":0.012150585609624,
        "system":"Earth_Moon",
        "family":"L2_Butterfly_Northern",
        "Period":11.555291205753774,
        "Jacobi":2.745412360915097,
        "Stability":1.000000000003475,
        "state_x":0.940999792653558,
        "state_y":-1.02198464448071e-21,
        "state_z":0.509474299789634,
        "state_vx":0.000000000000002,
        "state_vy":-0.12496802037539,
        "state_vz":0.000000000000028
    },
    "1":{
        "mu":0.012150585609624,
        "system":"Earth_Moon",
        "family":"L2_Butterfly_Northern",
        "Period":11.545291205753774,
        "Jacobi":2.747618763012661,
        "Stability":1.000000000003555,
        "state_x":0.942459953010378,
        "state_y":-5.01931178153858e-20,
        "state_z":0.507105298571933,
        "state_vx":0.000000000000002,
        "state_vy":-0.126877713881638,
        "state_vz":0.000000000000035
    },

Read JSON as DataFrame

As a precaution when reading the created JSON, use the same orient option as when saving to the `pd.read_json ()` option.

import pandas as pd
path = "/data_storage/my_data.json"
df_loaded = pd.read_json(path, orient="index")

If this orient is incorrect, columns and rows will be swapped and read: image.png

Recommended Posts

[Pandas] Save DataFrame as JSON, load JSON as DataFrame
Save Pandas DataFrame as .csv.gz in Amazon S3
Load nested json with pandas
Download Pandas DataFrame as a CSV file
3D plot Pandas DataFrame
Python application: Pandas # 3: Dataframe
Formatted display of pandas DataFrame
Export pandas dataframe to excel
[Python3] Save the mean and covariance matrix in json with pandas