Quantcast
Channel: dictionaryタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 99

pandasのセルのなかにdictionaryが!

$
0
0

ある日pandasのread_jsonで辞書形式のデータを読み込んでて気づいたもの。

1.起

こういうデータを

 [{"label":"20/00","x":297.0729064941406,"y":-385.3456726074219,"id":"145", "attributes":{"time":"1530"},"color":"rgb(153,153,153)","size":16.59930992126465},{"label":"10/04","x":4398.1484375,"y":-2204.3076171875,"id":"2692","attributes":{"time":"2460"},"color":"rgb(153,153,153)","size":4.0},・・・略・・・}]

こう読み込んだ。

df = pd.read_json("20153_nodes.json",orient="records")

ふとdfで出力してみるとセルの中に辞書っぽいものが!

image.png

attribute…ほんとは辞書の中の値を取り出したいのに。
どうも辞書の中に辞書形式でデータが入ってたようで。

2.承

まあstr⇒置換しちゃえばいいやと思ったらできない!(NaNになってしまう)
辞書で入っている!

df['attributes'] = df['attributes'].str.replace("{'time", "")

image.png

3.転

ネット上でそれらしき情報があったので、参考に。しかし意味不明の日本語。結果として無事にできました。

df["attributes"] = df["attributes"].apply(pd.Series)

image.png

4.結

pandasってネスト状態の辞書もちゃんとそのまま読み込むんだなーと感心。
今回はネスト内で値が1つしかなかったけど、複数あっても上記方法で分解してから、
mergeかjoinで連結すればもとのdfにひっつけられますね。


Viewing all articles
Browse latest Browse all 99

Trending Articles