LoginSignup
3
1

More than 1 year has passed since last update.

pandas で json の読み書き

Last updated at Posted at 2018-10-01

json の作成

json_create.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	json_create.py
#
#					Oct/01/2018
# ------------------------------------------------------------------
import sys
import pandas as pd
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
df = pd.DataFrame({'t0921': ["宇都宮",41295,"2003-8-12"],
		't0922': ["小山",41298,"2003-8-12"],
		't0923': ["佐野",31925,"2003-5-20"],
		't0924': ["足利",57418,"2003-4-18"],
		't0925': ["日光",71696,"2003-7-9"]},
	index=['name', 'population', 'date_mod'])

print(df)
#
path="./cities.json"
#
df.to_json(path)
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

作成される json

cities.json
{
  "t0921": {
    "name": "宇都宮",
    "population": 41295,
    "date_mod": "2003-8-12"
  },
  "t0922": {
    "name": "小山",
    "population": 41298,
    "date_mod": "2003-8-12"
  },
  "t0923": {
    "name": "佐野",
    "population": 31925,
    "date_mod": "2003-5-20"
  },
  "t0924": {
    "name": "足利",
    "population": 57418,
    "date_mod": "2003-4-18"
  },
  "t0925": {
    "name": "日光",
    "population": 71696,
    "date_mod": "2003-7-9"
  }
}

json の読み込み

json_read.py
#! /usr/bin/python
# -*- coding: utf-8 -*-
#
#	json_read.py
#
#					Oct/01/2018
# ------------------------------------------------------------------
import sys
import pandas as pd
#
# ------------------------------------------------------------------
sys.stderr.write("*** 開始 ***\n")
#
file_json = "./cities.json"
#
df=pd.read_json(file_json)
print(df)
#
df.to_json("tmp001.json")
#
sys.stderr.write("*** 終了 ***\n")
# ------------------------------------------------------------------

実行結果

$ ./json_read.py
*** 開始 ***
                t0921      t0922      t0923      t0924     t0925
date_mod    2003-8-12  2003-8-12  2003-5-20  2003-4-18  2003-7-9
name              宇都宮         小山         佐野         足利        日光
population      41295      41298      31925      57418     71696
*** 終了 ***

確認したバージョン

$ python
Python 3.10.9 (main, Dec 19 2022, 17:35:49) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pandas
>>> pandas.__version__
'1.5.3'
3
1
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
3
1