Python pandas 持久化缓存

18

是否有Python Pandas的实现,可以将数据缓存在磁盘上,以避免每次重新生成?

特别是对于财务中的get_yahoo_data是否有缓存方法?

一个非常好的额外功能:

  • 编写的代码行数很少
  • 当从同一来源下载新数据时,可以集成持久化序列
3个回答

21

有许多方法可以实现这一点,但可能最简单的方法是使用内置的方法来编写和读取Python pickles。您可以使用pandas.DataFrame.to_pickle将DataFrame存储到磁盘中,使用pandas.read_pickle从磁盘中读取所存储的DataFrame。

以下是一个pandas.DataFrame的示例:

# Store your DataFrame
df.to_pickle('cached_dataframe.pkl') # will be stored in current directory

# Read your DataFrame
df = pandas.read_pickle('cached_dataframe.pkl') # read from current directory

这些方法同样适用于pandas.Series

# Store your Series
series.to_pickle('cached_series.pkl') # will be stored in current directory

# Read your DataFrame
series = pandas.read_pickle('cached_series.pkl') # read from current directory

8
你可以使用 Data cache 包。
from data_cache import pandas_cache

@pandas_cache
def foo():
    ...

1
是的 <3 - Little Bobby Tables

4
依据不同的需求,有十几种方法可以实现,来回转换,使用CSV、Excel、JSON、Python Pickle格式、HDF5甚至带有DB的SQL等等。
在代码行方面,to/read许多这些格式只需要一行代码即可完成双向转换。Python和Pandas已经尽可能地简化了代码,因此您可以不用太担心。
我认为没有一种通用的解决方案适用于所有需求,真正的情况是因情况而异:
  • 对于保存数据的人类可读性:CSV、Excel
  • 用于二进制Python对象序列化(用例):Pickle
  • 用于数据交换:JSON
  • 用于长时间和增量更新:SQL
  • 等等。

如果您想每天更新股票价格并进行后续使用,我建议使用Pandas with SQL Queries,当然这将添加几行代码来设置数据库连接:

from sqlalchemy import create_engine

new_data = getting_daily_price()
# You can also choose other db drivers instead of `sqlalchemy`
engine = create_engine('sqlite:///:memory:')
with engine.connect() as conn:
    new_data.to_sql('table_name', conn) # To Write
    df = pd.read_sql_table('sql_query', conn) # To Read

1
我使用Python来避免编写大量代码,哪种解决方案在代码行数方面更好且更便宜? - Luca C.
@LucaC。我根据你更新的问题重新编写了答案。希望这样更有帮助。 - YaOzI
以下是几种序列化方法的速度比较。我认为由于可读性、速度和安全性,JSON 是最佳选择。https://www.benfrederickson.com/dont-pickle-your-data/ - user4815162342

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接