3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

pandasでネストされたjsonを読み込む

Last updated at Posted at 2020-09-29

pandasでネストされたjsonを読み込む
read nested json with pandas

環境

Google Corab

事象

pandasで、

import pandas as pd
pd.read_json('file.json')

をしたときに、

index title content
1 aaa {"col1": "a", "col2": "aa"...
2 bbb {"col1": "b", "col2": "bb"...

のようになるjsonファイルがあったとします。(contentに更にjson形式の文字列が入れ子になって格納された形です。)

これを、

col1 col2
a aa
b bb

と読み込みたかったんですね。

normalizeとかflattenとかで少し検索したらpd.json_normalize('file.json')がそれっぽかったので使ってみたところ、AttributeError: 'str' object has no attribute 'values'と怒られてしまいました。

解決方法

試行錯誤の末、

import pandas as pd
df = pd.read_json('file.json')
df = pd.DataFrame(df.content.to_list())

で正しく読み込めたので記事にしておきます。

3
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
3
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?