指定index=False仍生成索引?Pandas写入HDF文件问题求助
Pandas 1.5.1 to_hdf指定index=False仍出现索引列的问题解决
问题原因
你使用的format='table'是基于PyTables的表格存储格式,这种模式下,即使指定了index=False,PyTables会自动生成一个名为index的内置列(小写)作为行标识符,用于支持后续查询、切片等操作。这个列并非DataFrame本身的索引,而是PyTables为table格式自动添加的元列。
解决方案
根据你的使用需求,可选择以下两种方案:
方案1:改用fixed格式
如果不需要后续对HDF文件进行查询、筛选操作,将format='table'替换为format='fixed'。fixed格式以固定结构存储DataFrame,不会自动添加额外索引列,完全遵循index=False的设置:
df_total.to_hdf(os.path.join(target), key='Data', mode='w', format='fixed', index=False, data_columns=('year','month','day','hour','min','sec','recno','kindat','kinst', 'ut1_unix','ut2_unix','call_sign_tx','txlat','txlon','call_sign_rx', 'rxlat','rxlon','tfreq','sn','smode','ssrc','pthlen','latcen','loncen'), complevel=9, complib='zlib')
方案2:保留table格式并移除自动生成的index列
如果必须使用table格式(需支持查询功能),可通过PyTables库直接操作HDF文件删除自动生成的index列:
import tables # 原写入代码保持不变 df_total.to_hdf(os.path.join(target), key='Data', mode='w', format='table', index=False, data_columns=('year','month','day','hour','min','sec','recno','kindat','kinst', 'ut1_unix','ut2_unix','call_sign_tx','txlat','txlon','call_sign_rx', 'rxlat','rxlon','tfreq','sn','smode','ssrc','pthlen','latcen','loncen'), complevel=9, complib='zlib') # 打开HDF文件并删除自动生成的index列 with tables.open_file(os.path.join(target), mode='a') as h5file: table = h5file.root.Data.table table.remove_column('index') table.flush()
注意:删除该列后,后续用Pandas读取时建议指定drop_index=True,避免读取错误。
内容的提问来源于stack exchange,提问作者Bill
相关产品推荐
相关产品推荐

