创建空数据框的熊猫错误

Shi*_*ngh 20 python dataframe pandas

我尝试制作一个虚拟数据框,

column_names = ["a", "b", "c"]

df = pd.DataFrame(columns = column_names)

我收到以下错误,这以前没有发生过,我是不是遗漏了什么。这仅在创建空数据帧时发生,这是最近引入的错误。

  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.7/site-packages/pandas/core/frame.py", line 411, in __init__
    mgr = init_dict(data, index, columns, dtype=dtype)
  File "/usr/local/lib/python3.7/site-packages/pandas/core/internals/construction.py", line 242, in init_dict
    val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype)
  File "/usr/local/lib/python3.7/site-packages/pandas/core/dtypes/cast.py", line 1221, in construct_1d_arraylike_from_scalar
    dtype = dtype.dtype
AttributeError: type object 'object' has no attribute 'dtype'

Run Code Online (Sandbox Code Playgroud)

示例代码

Shi*_*ngh 20

这是发生在pandas==0.25.3 更新到最新pandas==1.2.1

更新:这是由于 numpy 包1.20.0,所以我锁定了 numpy 包numpy==1.19.5pandas==0.25.3

如果你想知道为什么你不想不必要地更新包,参考这个,https://medium.com/@singhnight/how-not-to-resolve-package-related-issues-7544c3a44dc


San*_*uhh 6

如果由于某种原因您不/不能升级 numpy/pandas,另一种解决此问题的方法是在创建 DataFrame 时指定 dtype。例如:

column_names = ["a", "b", "c"]
df = pd.DataFrame(columns = column_names, dtype=object)
Run Code Online (Sandbox Code Playgroud)


Gil*_*azi 5

因 发生numpy==1.20.0,并解决numpy==1.19.5。pandas 版本可能不相关,就我而言,pandas==1.0.4