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 2.3.2: `pandas.DataFrame({"a":[])`のdtypeはobjectでなくfloat64

Last updated at Posted at 2025-08-31

環境

  • Python 3.13.1
  • pandas 2.3.2

ハマったこと

columnが存在する空のDataFrameを生成したいです。

columns引数に列名を指定すると、dtypeはobjectでした。この挙動は期待通りです。

In [8]: df_a = pandas.DataFrame(columns=["x"])

In [9]: df_a.dtypes
Out[9]:
x    object
dtype: object

しかし、data引数にkeyが列名でvalueが空リストのdictを渡すと、dtypeはfloat64でした。

In [14]: df_b = pandas.DataFrame(data={"x":[]})

In [15]: df_b.dtypes
Out[15]:
x    float64
dtype: object

data引数に加えてcolumns引数に列名を指定しても、結果は変わりませんでした。

In [16]: df_b2 = pandas.DataFrame(data={"x":[]}, columns=["x"])

In [17]: df_b2.dtypes
Out[17]:
x    float64
dtype: object

df_adf_bx列を軸にしてmergeする処理で、df_b2が0件のときだけ以下のValueErrorが発生しました。このことがきっかけで、上記の挙動に気づきました。

In [58]: df_a.merge(df_b,on="x")
...
ValueError: You are trying to merge on object and float64 columns for key 'x'. If you wish to proceed you should use pd.concat

関連issue

issueには上がっていますが、まだ解決されていません。
https://github.com/pandas-dev/pandas/issues/56679

似た挙動

In [62]: pandas.array([])
Out[62]:
<FloatingArray>
[]
Length: 0, dtype: Float64

https://github.com/pandas-dev/pandas/issues/56679#issuecomment-2094789661 を参考にしました。

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?