pandasでDataFrameをフォーマット済みのJSON形式で出力する

オプションのindentを指定すればOK

df.to_json('example.json', orient='index', indent=2 )

ちなみに、JSONがひらがな等の非ascii文字を含む場合は出力時にUnicodeエスケープされてしまうが、これを回避したい場合はオプションにforce_ascii=Falseを追加すれば良い。

df.to_json('example.json', orient='index', indent=2, force_ascii=False)

関連リンク

ドキュメント: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_json.html
stackoverflow: https://stackoverflow.com/questions/53523083/how-to-write-dataframe-in-json-in-pretty-print-style

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


This site uses Akismet to reduce spam. Learn how your comment data is processed.