pandas.DataFrame.convert\u使用HDFStore的数据类型导致属性错误?

2024-09-29 02:18:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过convert\u dtypes转换df的数据类型,但如果我想通过HDFStore存储它,我会得到以下结果:AttributeError:“IntegerArray”对象没有属性“size”

df = pd.DataFrame()
df["test"] = [0,1,2,3]
df["test1"] = [0,1,2,3.5]
df = dfdf.convert_dtypes()
store=pd.HDFStore(r"C:\Users\User\Desktop\test.h5")
store["test"] = df
store.close()

Tags: 对象storetestconvertdataframedfsize属性
1条回答
网友
1楼 · 发布于 2024-09-29 02:18:00

我也经历过同样的问题。IntegerArray具有可以表示NAN的属性(类似于float64),这在pandas中的正常numpy int数据类型中是不可能的。但是,这会导致写入HDF时此数据类型失败。请参见此处(https://github.com/pandas-dev/pandas/issues/26144)。如果您的列中没有任何NAN,以下是一个简单而快速的解决方案:

cols = df.columns
for col in cols:
    col_dtype = df[col].dtype 
    try:               
        if col_dtype == pd.Int8Dtype():
            df[col] = df[col].astype('int8')
        elif col_dtype == pd.Int16Dtype():
            df[col] = df[col].astype('int16')
        elif col_dtype == pd.Int32Dtype():
            df[col] = df[col].astype('int32')    
        elif col_dtype == pd.Int64Dtype():
            df[col] = df[col].astype('int64')
    except:
        pass


相关问题 更多 >