我有一个 2Gb 的数据帧,一次写入,多次读取 df。
我想在 pandas 中使用 df,因此我使用了固定格式的 df.read_hdf
和 df.to_hdf
,在读写方面效果很好。
但是,df随着列的增加而增长,所以我想改用表格格式,这样我可以在读取数据时选择我需要的列。我认为这会给我带来速度优势,但从测试来看情况似乎并非如此。
这个例子:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(10000000,9),columns=list('ABCDEFGHI'))
%time df.to_hdf("temp.h5", "temp", format ="fixed", mode="w")
%time df.to_hdf("temp2.h5", "temp2", format="table", mode="w")
显示固定格式稍快(在我的机器上为 6.8 秒对 5.9 秒)。
然后读取数据(稍作休息以确保文件已完全保存):
%time x = pd.read_hdf("temp.h5", "temp")
%time y = pd.read_hdf("temp2.h5", "temp2")
%time z = pd.read_hdf("temp2.h5", "temp2", columns=list("ABC"))
产量:
Wall time: 420 ms (fixed)
Wall time: 557 ms (format)
Wall time: 671 ms (format, specified columns)
我明白固定格式读取数据的速度更快,但为什么 具有指定列的 df 比读取完整数据帧慢?与固定格式相比,使用表格格式(带或不带指定列)有什么好处?
当 df 变得更大时,是否可能存在内存优势?
最佳答案
IMO 将 format='table'
与 data_columns=[list_of_indexed_columns]
结合使用的主要优势是能够有条件地(参见 where="where子句”
参数)读取巨大的 HDF5 文件。这样您就可以在阅读时过滤您的数据,并分块处理您的数据以避免内存错误。
您可以尝试将单个列或列组(大多数情况下会一起阅读的列)保存在不同的 HDF 文件中,或者保存在具有不同键的同一文件中。
我还会考虑使用“尖端”技术 - Feather-Format
测试和计时:
import feather
以三种格式写入磁盘:(HDF5 fixed、HDF% table、Feather)
df = pd.DataFrame(np.random.randn(10000000,9),columns=list('ABCDEFGHI'))
df.to_hdf('c:/temp/fixed.h5', 'temp', format='f', mode='w')
df.to_hdf('c:/temp/tab.h5', 'temp', format='t', mode='w')
feather.write_dataframe(df, 'c:/temp/df.feather')
从磁盘读取:
In [122]: %timeit pd.read_hdf(r'C:\Temp\fixed.h5', "temp")
1 loop, best of 3: 409 ms per loop
In [123]: %timeit pd.read_hdf(r'C:\Temp\tab.h5', "temp")
1 loop, best of 3: 558 ms per loop
In [124]: %timeit pd.read_hdf(r'C:\Temp\tab.h5', "temp", columns=list('BDF'))
The slowest run took 4.60 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 689 ms per loop
In [125]: %timeit feather.read_dataframe('c:/temp/df.feather')
The slowest run took 6.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1 loop, best of 3: 644 ms per loop
In [126]: %timeit feather.read_dataframe('c:/temp/df.feather', columns=list('BDF'))
1 loop, best of 3: 218 ms per loop # WINNER !!!
PS如果在使用feather.write_dataframe(...)
时遇到如下错误:
FeatherError: Invalid: no support for strided data yet
这里有一个解决方法:
df = df.copy()
在那之后 feather.write_dataframe(df, path)
应该可以正常工作...
关于python - 使用 pandas.to_hdf 快速读取 df 中的指定列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42021800/