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’告警

Pandas创建DataFrame提示: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

总结

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容