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.DataFrame.to_dict()`で値がどのように変換されるか

Last updated at Posted at 2025-09-01

環境

  • Python 3.13.1
  • pandas 2.3.2
  • numpy 2.2.4

概要

pandas.DataFrame.to_dict()を実行したときに、pd.NAなどの値がどのような値に変換されるかがドキュメントには書いていなかったので、実際に動かして確認しました。

結果

準備

In [38]: df = pd.DataFrame({"a":["bar", np.nan], "b":[1,None],"c":[1.1,None],"d":["bar",None]}).astype({"b":"Int64","d":"string"})

In [51]: df
Out[51]:
     a     b    c     d
0  bar     1  1.1   bar
1  NaN  <NA>  NaN  <NA>

In [39]: df.dtypes
Out[39]:
a            object
b             Int64
c           float64
d    string[python]
dtype: object

特殊な値がどう変換されるか

  • pd.NAはNoneに変換される
  • np.nanは変換されない。dtypeがobjectでも結果は変わらない
In [40]: records = df.to_dict("records")

In [41]: records
Out[41]:
[{'a': 'bar', 'b': 1, 'c': 1.1, 'd': 'bar'},
 {'a': nan, 'b': None, 'c': nan, 'd': None}]

typeがどう変換されるか

  • numpyの数値型はpythonの数値型に変換される
    • numpy.int64intに変換される
    • numpy.float64floatに変換される

numpy.int64intに変換されないと、json.dumpsで出力されないので、typeを確認しました。
詳細は https://qiita.com/yuji38kwmt/items/0a1503f127fc3be17be0 を参照してください。

In [44]: type(df["b"][0])
Out[44]: numpy.int64

In [45]: type(df["c"][0])
Out[45]: numpy.float64

In [42]: type(records[0]["b"])
Out[42]: int

In [43]: type(records[0]["c"])
Out[43]: float

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?