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?

`pandas.json_normalize([{"a":{}}])`で生成したDataFrameには`a`列は存在しない

Posted at

環境

  • Python 3.12.4
  • pandas 2.2.2

はじめに

ネストされているdictのlistをpandas.DataFrameで扱うため、pandas.json_normalizeを使ってpandas.DataFrameを生成しています。

In [104]: data=[{"a":{"x":1,"y":2}, "b":"alice"}, {"a":{"x":4}, "b":"bob"}]

In [108]: df = pandas.json_normalize(data)

In [109]: df
Out[109]:
       b  a.x  a.y
0  alice    1  2.0
1    bob    4  NaN

ハマったこと

変数data2のキーaの値は空のdictです。pandas.json_normalizeで生成した場合、a列にNoneが格納されることを期待したのですが、実際にはa列は存在しませんでした。

In [111]: data2 = [{"a":{}, "b":"alice"}]

In [115]: df2 = pandas.json_normalize(data2)

In [116]: df2
Out[116]:
       b
0  alice

ネストされたdictでも同様でした。

In [117]: data3 = [{"a":{"x":{}}, "b":"alice"}]

In [118]: df3 = pandas.json_normalize(data3)

In [119]: df3
Out[119]:
       b
0  alice

変数data4のキーcの値はNoneです。この場合は、DataFrameにc列は存在しました。

In [120]: data4 = [{ "b":"alice", "c":None}]

In [121]: df4 = pandas.json_normalize(data4)

In [122]: df4
Out[122]:
       b     c
0  alice  None
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?