LoginSignup
1
5

More than 3 years have passed since last update.

[Pandas] DataFrameをJSONとして保存、JSONをDataFrameとして読み込み

Posted at

三体問題内の解の計算は事前に済ませ、保存しておくことが多いので、保存方法について現時点でベストな手法を記録。
具体的な流れとしては、Python上でデータ作成(周期、state, system nameなど)→ pandas.DataFrameを作成 → DataFrameをJSONとして保存、のちにJSONをDataFrameとして読み込みする。

DataFrameをJSONとして書き出し

まず、DataFrameを用意
image.png
これをJSONとして保存するには

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

まず pathで保存先とファイル名、拡張子(もちろん.json)を入力。オプションについては、orient="index"でSeries毎に保存しており、indend="4"でSeries毎にJSONファイル内で改行してくれる。結果はこんな感じ

{
    "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
    },

JSONをDataFrameとして読み込み

作成したJSONを読み取るときの注意点としては、pd.read_json()のオプションに保存した時と同じorientのオプションを使うこと。

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

このorientが正しくないと、columnsとrowsが入れ替わって読み込んでしまう:
image.png

1
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
5