0
0

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形式の列データを複数列に展開

Posted at

レコードの中がJSONフォーマットから要素を抽出したい#

データの中の列データがJSON 文字列だったのでその前処理をするため下の記事を参考にやってみました

やりたいこと#

id label
123 {'a':1,'b':2}
456 {'a':6,'b':10}
789 {'a':4,'b':5}
元データがこんな感じだったので
id label a b
123 {'a':1,'b':2} 1 2
456 {'a':6,'b':10} 6 10
789 {'a':4,'b':5} 4 5
にしたい

実装#

とりあえず試してみる

import pandas as pd

data = {
    'json_col': ['{"a": 1, "b": 2}', '{"a": 6, "b": 10}','{"a": 4, "b": 5}']
}

df = pd.DataFrame(data)
df.head()

上記の記事を参考に

from pandas.io.json import json_normalize
import json 

df_json = json_normalize(df['json_col'].apply(lambda x: json.loads(x)))
df_json.head()

うまくいったので自分のデータ(CSVファイル)でやってみると
AttributeError: 'list' object has no attribute 'items'
とエラーが出ました。

エラーの原因#

いろいろ調べて下記の記事を見つけました。
どうやらlist型やdict型を含むレコードがあるCSVは読み込んだ時にstr型になってしまう仕様らしい。。。

import ast

df['hoge2'] = [ast.literal_eval(d) for d in df['hoge']]

こいつを使ってstr型をlist型/dict型にして要素ごとに抽出しました。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?