Pandas pd.read_json() 関数

Python math 模块Pandas よく使う関数


read_json()pd.read_jsonは、pandasライブラリでJSON(JavaScript Object Notation)ファイルを読み取るための関数で、さまざまなJSON形式のデータインポートをサポートしています。

JSONは軽量なデータ交換形式で、人間が読み書きしやすく、機械が解析・生成しやすいという特徴があります。Web APIや設定ファイルなどの場面で広く使用されています。read_json()JSONデータをpandasのDataFrame形式に変換でき、データ分析に便利です。


基本構文とパラメータ

構文形式

pandas.read_json(path_or_buf, orient=None, typ='frame', dtype=None,
                convert_axes=None, convert_dates=True, keep_default_dates=True,
                numpy=False, precise_float=False, date_unit='ms', ...)

パラメータの説明

パラメータ型説明デフォルト値
path_or_bufstr、path object、またはfile-like objectJSONファイルのパス、URL、または文字列必須
orientstrJSONデータの形式:'split'、'records'、'index'、'columns'、'values'None
typstr戻り値の型:'frame'はDataFrameを返し、'series'はSeriesを返します'frame'
dtypedict列のデータ型を指定None
convert_axesbool軸を日時(datetime)に変換するかどうかNone
convert_datesbool, list日付列を変換するかどうかTrue
numpyboolnumpy配列を使用するかどうかFalse

戻り値

  • 戻り値の型:pd.DataFrame 或 pd.Series
  • デフォルトではDataFrameを返し、2次元の表形式になります。
  • 当 typ='series'orient='series'を指定した場合はSeriesを返します。

実例

以下の例を通して、完全に習得しましょうread_json()のさまざまな使い方を。

例1:さまざまな形式のJSONデータを読み取る

JSONデータにはさまざまな形式があり、read_json()pd.read_jsonは最も一般的ないくつかの形式をサポートしています。

実例

import pandas as pd
import json

# サンプルデータ:JSON配列形式(records format)
json_records = '''
[
    {"name": "Tom", "age": 28, "city": "Beijing", "salary": 8000},
    {"name": "Jerry", "age": 35, "city": "Shanghai", "salary": 12000},
    {"name": "Mike", "age": 42, "city": "Guangzhou", "salary": 15000}
]
'''


# JSON文字列をファイルに書き込む
with open('data_records.json', 'w', encoding='utf-8') as f:
    f.write(json_records)

# JSONファイルを読み取る(records形式、最も一般的)
# orient='records' は各行が1つのJSONオブジェクトであることを示す
df_records = pd.read_json('data_records.json', orient='records')
print("Records形式:")
print(df_records)
print()

# サンプルデータ:JSONオブジェクト形式(index format)
json_index = '''
{
    "Tom": {"age": 28, "city": "Beijing", "salary": 8000},
    "Jerry": {"age": 35, "city": "Shanghai", "salary": 12000},
    "Mike": {"age": 42, "city": "Guangzhou", "salary": 15000}
}
'''


with open('data_index.json', 'w', encoding='utf-8') as f:
    f.write(json_index)

# JSONファイルを読み取る(index形式、指定フィールドをインデックスとする)
df_index = pd.read_json('data_index.json', orient='index')
print("Index形式:")
print(df_index)
print()

# サンプルデータ:JSON列形式(columns format)
json_columns = '''
{
    "name": ["Tom", "Jerry", "Mike"],
    "age": [28, 35, 42],
    "city": ["Beijing", "Shanghai", "Guangzhou"],
    "salary": [8000, 12000, 15000]
}
'''


with open('data_columns.json', 'w', encoding='utf-8') as f:
    f.write(json_columns)

# JSONファイルを読み取る(columns形式)
df_columns = pd.read_json('data_columns.json', orient='columns')
print("Columns形式:")
print(df_columns)

実行結果の想定:

Records 格式:
    name  age       city  salary
0    Tom   28    Beijing    8000
1  Jerry   35   Shanghai   12000
2   Mike   42  Guangzhou   15000

Index 格式:
         age       city  salary
Tom       28    Beijing    8000
Jerry    35   Shanghai   12000
Mike     42  Guangzhou   15000

Columns 格式:
    name  age       city  salary
0    Tom   28    Beijing    8000
1  Jerry   参数          Shanghai   12000
2   Mike   42  Guangzhou   15000

コードの解説:

  • orient='records'orient='records':JSON配列形式で、各行が1つのJSONオブジェクトであり、最も一般的な形式です。
  • orient='index'orient='index':JSONオブジェクト形式で、キーがインデックスになります。
  • orient='columns'orient='columns':JSON列形式で、キーが列名、値が配列になります。
  • orientパラメータを正しく指定することは、orientJSONデータを正しく解析するために極めて重要です。

例2:文字列とURLからJSONを読み取る

read_json()ファイルだけでなく、文字列やURLからもデータを読み取ることができます。

実例

import pandas as pd
import json
from io import StringIO

# 例2a: JSON文字列から読み取る
json_string = '''
[
    {"product": "A", "sales": 100, "region": "North"},
    {"product": "B", "sales": 200, "region": "South"},
    {"product": "C", "sales": 150, "region": "East"}
]
'''


# StringIOを使用して文字列をファイルオブジェクトに変換する
df_from_string = pd.read_json(StringIO(json_string))
print("文字列から読み取り:")
print(df_from_string)
print()

# パラメータにJSON文字列を直接渡すこともできます
# 注意:Pythonの文字列は正しくエスケープする必要があります
json_str_direct = '[{"product": "A", "sales": 100}, {"product": "B", "sales": 200}]'
df_direct = pd.read_json(json_str_direct)
print("文字列を直接渡す:")
print(df_direct)
print()

# 例2b: JSON Lines形式を読み取る(各行が1つのJSONオブジェクト)
# JSON Linesは一般的なログ形式です
json_lines = '''{"name": "Tom", "score": 85}
{"name": "Jerry", "score": 92}
{"name": "Mike", "score": 78}
{"name": "Lucy", "score": 95}'''


with open('data_lines.json', 'w', encoding='utf-8') as f:
    f.write(json_lines)

# JSON Lines形式は1行ずつ読み取る必要があります
# lines=Trueパラメータを使用できます(JSONL形式がサポートしている場合)
# または手動で処理します
df_list = []
with open('data_lines.json', 'r', encoding='utf-8') as f:
    for line in f:
        df_list.append(json.loads(line))

df_lines = pd.DataFrame(df_list)
print("JSON Lines形式の読み取り:")
print(df_lines)
print()

# 例2c: APIのURLから読み取る(ネットワークアクセスが必要)
# ここではサンプルAPIを使用しています。実際に使用する際は実際のURLに置き換えてください
# df_api = pd.read_json('https://api.example.com/data')
# print(df_api)
print("注意:URLから読み取るには実際のネットワークリクエストが必要です")

実行結果の想定:

从字符串读取:
  product  sales region
0       A    100   North
1       B    200   South
2       C    150    East

直接传入字符串:
  product  sales
0       A    100
1       B    200

JSON Lines 格式读取:
    name  score
0    Tom     85
1  Jerry     92
2    Mike     78
3    Lucy     95

注意:从 URL 读取需要实际的网络请求

コードの解説:

  • read_json()pd.read_jsonはJSON文字列を入力として受け付けることができ、StringIOを使用してStringIO文字列をファイルライクオブジェクトに変換します。
  • JSON Lines形式は、各行が独立したJSONオブジェクトであり、ログ処理でよく使用されます。1行ずつ読み取ってからDataFrameに結合する必要があります。
  • URLから読み取る場合は、URL文字列を直接渡すだけでよいですが、ネットワーク接続が必要です。

例3:日付の処理と型変換

JSONデータ内の日付や数値型は特別な処理が必要です。

実例

import pandas as pd

# 例3a: 日付フィールドの処理
json_with_date = '''
[
    {"name": "Tom", "birthday": "1995-03-15", "join_date": "2020-01-10"},
    {"name": "Jerry", "birthday": "1988-07-22", "join_date": "2019-03-05"},
    {"name": "Mike", "birthday": "1981-11-30", "join_date": "2018-06-20"}
]
'''


with open('data_with_date.json', 'w', encoding='utf-8') as f:
    f.write(json_with_date)

# デフォルトでは日付文字列がobject型として読み取られます
df_date = pd.read_json('data_with_date.json')
print("デフォルトの読み取り(日付は文字列):")
print(df_date)
print("birthdayの型:", df_date['birthday'].dtype)
print()

# convert_datesを使用して日付列を自動変換する
df_date_converted = pd.read_json('data_with_date.json', convert_dates=['birthday', 'join_date'])
print("日付変換後:")
print(df_date_converted)
print("birthdayの型:", df_date_converted['birthday'].dtype)
print()

# 例3b: データ型の指定
json_mixed = '''
[
    {"id": "1", "name": "Tom", "score": 85.5},
    {"id": "2", "name": "Jerry", "score": 92.0},
    {"id": "3", "name": "Mike", "score": 78.5}
]
'''


with open('data_mixed.json', 'w', encoding='utf-8') as f:
    f.write(json_mixed)

# デフォルトではidは整数、nameは文字列、scoreは浮動小数点数として読み取られます
df_mixed = pd.read_json('data_mixed.json')
print("デフォルトの型推論:")
print(df_mixed)
print("idの型:", df_mixed['id'].dtype)
print()

# dtypeを使用して型を明示的に指定する
df_typed = pd.read_json('data_mixed.json', dtype={'id': str, 'score': float})
print("型指定後:")
print(df_typed)
print("idの型:", df_typed['id'].dtype)

実行結果の想定:

默认读取(日期为字符串):
    name    birthday    join_date
0    Tom  1995-03-15  2020-01-10
1  Jerry  1988-07-22  2019-03-05
2    Mike  1981-11-30  2018-06-20

默认读取(日期为字符串):
    name    birthday    join_date
0    汤    Tom  1995-03-15  pandas 的 to_json() 和 read_json() 的完整配对示例
1  Jerry  1988-07-22  2019-03-05
2    Mike  1981-11-30  确保 JSON 数据格式一致
    1981-配对    to_json(orient='records')  配对    read_json(orient='records')
3   Mike  1981-11-30  to_json(orient='records')
...
    join_date    2018-06-20

birthday 类型: object

转换日期后:
birthday 类型: datetime64[ns]

コードの解説:

  • convert_datesconvert_datesパラメータで、日付型に変換する列を指定できます。
  • デフォルトでは、convert_dates=Trueconvert_datesは一般的な日付形式を自動的に認識します。
  • dtypedtypeパラメータで各列のデータ型を明示的に指定でき、型推論のエラーを防げます。

注意事項

  • orientパラメータを正しく指定することは、orientJSONデータを読み取る鍵であり、JSONの構造によって異なるorient値が必要です。
  • JSON内の日付はデフォルトで文字列として読み取られるため、convert_datesパラメータをconvert_dates使用して日付型に変換する必要があります。
  • 大きなJSONファイルを読み取る場合は、chunksizeパラメータをchunksize使用してチャンク単位で読み取ることを検討できます。
  • read_json()ファイルパス、URL、JSON文字列からの読み取りをサポートしています。
  • JSON Lines形式は1行ずつ解析した後、DataFrameに結合する必要があります。

まとめ

read_json()pd.read_jsonは、pandasでJSONデータを読み取る中核となる関数で、さまざまなJSON形式をサポートしています。JSONはWeb APIやデータ交換の一般的な形式として、実際のデータ分析業務で広く使用されています。

pd.read_jsonを習得するread_json()鍵は、さまざまなorient形式を理解し、orient日付や型の処理方法を把握することです。実際の作業でさまざまな形式のJSONデータの読み取りを練習することをお勧めします。

Python math 模块Pandas よく使う関数

その他の拡張