【问题标题】:Python 2.7: Appending Data to Table in PandasPython 2.7:在 Pandas 中将数据附加到表中
【发布时间】:2014-03-28 22:12:24
【问题描述】:

我正在从图像文件中读取数据,并且我想将此数据附加到单个 HDF 文件中。这是我的代码:

datafile = pd.HDFStore(os.path.join(path,'imageData.h5'))
for file in fileList: 
     data = {'X Position' :  pd.Series(xpos, index=index1),
             'Y Position' :  pd.Series(ypos, index=index1),
             'Major Axis Length' :  pd.Series(major, index=index1),
             'Minor Axis Length' :  pd.Series(minor, index=index1), 
             'X Velocity' :  pd.Series(xVelocity, index=index1),
             'Y Velocity' :  pd.Series(yVelocity, index=index1) }
    df = pd.DataFrame(data)
    datafile['df'] = df
    datafile.close()

这显然是不正确的,因为每次循环运行时它都会用新数据覆盖每组数据。

如果不是datafile['df'] = df,我使用

datafile.append('df',df)    

df.to_hdf(os.path.join(path,'imageData.h5'), 'df', append=True, format = 'table')

我得到错误:

ValueError: Can only append to Tables

我已经提到了documentation 和其他SO questions,但无济于事。

所以,我希望有人能解释为什么这不起作用,以及如何成功地将所有数据附加到一个文件中。如有必要,我愿意使用不同的方法(可能是 pyTables)。

任何帮助将不胜感激。

【问题讨论】:

  • 第二种方式(df.to_hdf(..., format="table", append=True))其实是正确的。您是否尝试过将它(没有所有 HDFStore 的东西)与新文件一起使用?
  • @filmor 你的意思是删除我创建空 HDF 文件的行?试过了,同样的错误。也许问题在于数据在 DataFrame 中而不是在表中?
  • 否,错误消息是指使用的内部 HDF5 表格式。旧版 pandas 中的 IIRC(顺便说一句,您使用的是哪一个?)HDFStore 默认使用不允许附加的fixed 格式。 table 格式是 PyTables 使用的格式。
  • 版本 0.11.0 - 我在一个新文件上尝试过,它可以工作,但没有 for 循环。
  • 如果你使用 format="table" to_hdf 应该允许在内部使用 PyTables 进行追加,不需要自己做。不过,您可能想要更新 pandas。 “并且成功了”是什么意思?你会更新问题吗?

标签: python pandas hdf5 pytables


【解决方案1】:

这将在 0.11 中工作。创建组后(例如,您存储数据的标签,此处的“df”)。如果您存储 fixed 格式,它将覆盖(如果您尝试附加,则会给您上述错误消息);如果你写一个table 格式你可以追加。请注意,在 0.11 中,to_hdf 无法正确地将关键字传递给底层函数,因此您只能使用它来编写 fixed 格式。

datafile = pd.HDFStore(os.path.join(path,'imageData.h5'),mode='w')
for file in fileList: 
     data = {'X Position' :  pd.Series(xpos, index=index1),
             'Y Position' :  pd.Series(ypos, index=index1),
             'Major Axis Length' :  pd.Series(major, index=index1),
             'Minor Axis Length' :  pd.Series(minor, index=index1), 
             'X Velocity' :  pd.Series(xVelocity, index=index1),
             'Y Velocity' :  pd.Series(yVelocity, index=index1) }
    df = pd.DataFrame(data)
    datafile.append('df',df)
datafile.close

【讨论】:

  • 完美,谢谢。我必须做的唯一更改是在追加之前添加datafile.open()
  • 为了清楚起见,这里唯一的区别是在第一行添加了mode='w'。那么,默认模式是什么?
  • 默认模式是追加(到文件); w 创建一个新文件
猜你喜欢
  • 1970-01-01
  • 2022-08-06
  • 1970-01-01
  • 2017-11-22
  • 2017-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-17
相关资源
最近更新 更多