Pandas DataFrame を JSON ファイルにエクスポートするには:

df.to_json(r"Path to store the exported JSON file\File Name.json")

手順

ステップ1: DataFrameを作成する

製品と価格に関するデータが含まれる次の DataFrame があるとします。

import pandas as pd

data = {
    "Product": ["Computer", "Printer", "Monitor", "Tablet", "Keyboard"],
    "Price": [1200, 200, 500, 350, 80],
}

df = pd.DataFrame(data)

print(df)

Python でコードを実行すると、次の DataFrame が取得されます。

Pandas DataFrame を JSON ファイルにエクスポートする

ステップ2: DataFrameをJSONファイルにエクスポートする

Pandas DataFrame を JSON ファイルにエクスポートするには:

df.to_json(r"Path to store the exported JSON file\File Name.json")

たとえば、JSON ファイルがエクスポートされるパスが次のとおりであるとします。

C:\Users\Ron\Desktop\my_data.json

したがって、DataFrame を JSON ファイルにエクスポートするための完全なコードは次のようになります。

import pandas as pd

data = {
    "Product": ["Computer", "Printer", "Monitor", "Tablet", "Keyboard"],
    "Price": [1200, 200, 500, 350, 80],
}

df = pd.DataFrame(data)

df.to_json(r"C:\Users\Ron\Desktop\my_data.json")

コードを実行すると(パスに合わせて調整されます)、JSON ファイルが指定した場所に保存されます。

JSONコンテンツを表示する方法はいくつかあります。簡単な方法は、作成したファイルをWebブラウザにドラッグすることです。すると、次のような結果が表示されます。

{“Product”:{“0″:”Computer”,”1″:”Printer”,”2″:”Monitor”,”3″:”Tablet”,”4″:”Keyboard”},”Price”:{“0″:1200,”1″:200,”2″:500,”3″:350,”4”:80}}

さまざまなJSON形式

JSON文字列をフォーマットする方法はいくつかあります。希望する形式に合わせてorientを設定する必要があります。以下のオプションがあります。

  • スプリット
  • 記録
  • 索引
  • 価値観
  • テーブル
  • 列(デフォルトの形式)

たとえば、「分割」方向を取得するには、orient = “split”を設定します。

import pandas as pd

data = {
    "Product": ["Computer", "Printer", "Monitor", "Tablet", "Keyboard"],
    "Price": [1200, 200, 500, 350, 80],
}

df = pd.DataFrame(data)

df.to_json(r"C:\Users\Ron\Desktop\my_data.json", orient="split")

結果:

{“columns”:[“Product”,”Price”],”index”:[0,1,2,3,4],”data”:[[“Computer”,1200],[“Printer”,200],[“Monitor”,500],[“Tablet”,350],[“Keyboard”,80]]}

他の各形式で得られる結果は次のとおりです。

orient=”records”

{“0”:{“Product”:”Computer”,”Price”:1200},”1″:{“Product”:”Printer”,”Price”:200},”2″:{“Product”:”Monitor”,”Price”:500},”3″:{“Product”:”Tablet”,”Price”:350},”4″:{“Product”:”Keyboard”,”Price”:80}}

orient=”index”

[{“Product”:”Computer”,”Price”:1200},{“Product”:”Printer”,”Price”:200},{“Product”:”Monitor”,”Price”:500},{“Product”:”Tablet”,”Price”:350},{“Product”:”Keyboard”,”Price”:80}]

orient=”values”

[[“Computer”,1200],[“Printer”,200],[“Monitor”,500],[“Tablet”,350],[“Keyboard”,80]]

orient=”table”

{“schema”:{“fields”:[{“name”:”index”,”type”:”integer”},{“name”:”Product”,”type”:”string”},{“name”:”Price”,”type”:”integer”}],”primaryKey”:[“index”],”pandas_version”:”1.4.0″},”data”:[{“index”:0,”Product”:”Computer”,”Price”:1200},{“index”:1,”Product”:”Printer”,”Price”:200},{“index”:2,”Product”:”Monitor”,”Price”:500},{“index”:3,”Product”:”Tablet”,”Price”:350},{“index”:4,”Product”:”Keyboard”,”Price”:80}]}

orient=”columns”(default)

{“Product”:{“0″:”Computer”,”1″:”Printer”,”2″:”Monitor”,”3″:”Tablet”,”4″:”Keyboard”},”Price”:{“0″:1200,”1″:200,”2″:500,”3″:350,”4”:80}}