我有一个2Gb的数据,这是一个写一次,读了很多df。我想在熊猫上使用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.8s vs 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变得更大时,可能有记忆优势吗?
发布于 2017-02-03 10:27:25
与format='table'结合使用data_columns=[list_of_indexed_columns]的主要优点是能够有条件地(参见where="where clause"参数)读取巨大的HDF5文件。这样,您就可以在读取时过滤数据,并以块的形式处理数据,以避免MemoryError。
您可以尝试将单个列或列组(大部分时间将一起读取的列或列组)保存在不同的HDF文件或具有不同键的同一文件中。
我还会考虑使用“尖端”技术- 羽式。
测试与计时:
import feather以三种格式写入磁盘:(HDF5固定的,HDF%表,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 !!!如果在使用feather.write_dataframe(...)时遇到以下错误,则为PS
FeatherError: Invalid: no support for strided data yet 以下是一个解决办法:
df = df.copy()在那之后,feather.write_dataframe(df, path)应该正常工作..。
https://stackoverflow.com/questions/42021800
复制相似问题