Pandas创建DataFrame提示:type object 'object' has no attribute 'dtype'解决方案

2023-02-09

Pandas数据帧(DataFrame)是二维数据结构,它包含一组有序的列,每列可以是不同的数据类型,这篇文章主要给大家介绍了关于Pandas创建DataFrame提示:type object ‘object‘ has no attribute ‘dtype‘的解决方案,需要的朋友可以参考下

目录
  • 发现问题
  • 原因分析:
  • 解决方案:
  • 总结

发现问题

pandas版本0.25.3

import pandas as pd

symbol_info_columns = ['1', '持仓方向', '持仓量', '持仓收益率', '持仓收益', '持仓均价', '当前价格', '最大杠杆']  # v3
symbol_config = {'BTC': 'BTC-USDT-210924', 'LTC': 'LTC-USDT-210924', 'EOS': 'EOS-USDT-210924', 'ETH': 'ETH-USDT-210924', 'XRP': 'XRP-USDT-210924', 'FIL': 'FIL-USDT-210924'}
symbol_info = pd.DataFrame()
# dates = pd.date_range('20190101', periods=6)
# num_df = pd.DataFrame(data=np.random.randn(6, 8), index=dates, columns=symbol_info_columns)
symbol_info = pd.DataFrame(index=symbol_config.keys(), columns=symbol_info_columns)

data为空,且dtype默认为空时

出现type object ‘object’ has no attribute 'dtype’告警

原因分析:

创建DataFrame时,data字段为空

会默认创建一个空字典作为data

    def __init__(self, data=None, index=None, columns=None, dtype=None, copy=False):
        if data is None:
            data = {}

然后初始化字典

elif isinstance(data, dict):
    mgr = init_dict(data, index, columns, dtype=dtype)

init_dict函数中:

columns非空,且dtype默认为None时,会赋值nan_dtype = object

if columns is not None:
	if missing.any() and not is_integer_dtype(dtype):
	    if dtype is None or np.issubdtype(dtype, np.flexible):
	        # GH#1783
	        nan_dtype = object

该object下无dtype方法

可能是object引用错误

解决方案:

pandas(版本0.25.3)init_dict函数位于

D:\Users\。。。\Anaconda3\envs\Python3.7\Lib\site-packages\pandas\core\internals\construction.py

参考Python3.9环境中pandas(版本1.2.5)

同名函数(D:\Users\。。。\Anaconda3\envs\Python3.7\Lib\site-packages\pandas\core\internals\construction.py)写法

nan_dtype = np.dtype(object)

可见该问题应该是pandas(版本0.25.3)的bug

总结

到此这篇关于Pandas创建DataFrame提示:type object 'object' has no attribute 'dtype'解决方案的文章就介绍到这了,更多相关Pandas创建DataFrame报错内容请搜索北冥有鱼以前的文章或继续浏览下面的相关文章希望大家以后多多支持北冥有鱼!

《Pandas创建DataFrame提示:type object 'object' has no attribute 'dtype'解决方案.doc》

下载本文的Word格式文档,以方便收藏与打印。