1
1

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 5 years have passed since last update.

pandasのセルのなかにdictionaryが!

Last updated at Posted at 2019-09-04

ある日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にひっつけられますね。

追記:dictionaryだけじゃなくlistでもOKだった。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?