现在,每次运行脚本时,我都会导入一个相当大的CSV作为数据框架。是否有一个好的解决方案来保持数据帧在运行之间不断可用,这样我就不必花费所有的时间等待脚本运行?
当前回答
如果我理解正确的话,你已经在使用pandas.read_csv(),但想要加快开发过程,这样你就不必每次编辑脚本时都加载文件,对吗?我有一些建议:
you could load in only part of the CSV file using pandas.read_csv(..., nrows=1000) to only load the top bit of the table, while you're doing the development use ipython for an interactive session, such that you keep the pandas table in memory as you edit and reload your script. convert the csv to an HDF5 table updated use DataFrame.to_feather() and pd.read_feather() to store data in the R-compatible feather binary format that is super fast (in my hands, slightly faster than pandas.to_pickle() on numeric data and much faster on string data).
您可能还会对stackoverflow上的答案感兴趣。
其他回答
这里有很多很棒和充分的答案,但我想发布一个我在Kaggle上使用的测试,这个测试用不同的pandas兼容格式保存和读取大df:
https://www.kaggle.com/pedrocouto39/fast-reading-w-pickle-feather-parquet-jay
我不是作者,也不是作者的朋友,然而,当我读到这个问题时,我觉得值得一提。
CSV: 1分42秒泡菜:4.45秒羽毛:4.35秒拼花:8.31秒杰伦:8.12毫秒 或者0.0812秒(超快的!)
您可以使用羽毛格式的文件。它非常快。
df.to_feather('filename.ft')
最简单的方法是使用to_pickle来pickle它:
df.to_pickle(file_name) # where to save it, usually as a .pkl
然后你可以使用以下命令将其加载回来:
df = pd.read_pickle(file_name)
注意:在0.11.1之前,save和load是唯一的方法(现在它们已被弃用,分别支持to_pickle和read_pickle)。
另一个流行的选择是使用HDF5 (pytables),它为大型数据集提供了非常快的访问时间:
import pandas as pd
store = pd.HDFStore('store.h5')
store['df'] = df # save it
store['df'] # load it
更高级的策略在烹饪书中讨论。
从0.13开始,也有msgpack,它可能在互操作性方面更好,作为JSON的更快替代品,或者如果你有python对象/文本较多的数据(参见这个问题)。
如果我理解正确的话,你已经在使用pandas.read_csv(),但想要加快开发过程,这样你就不必每次编辑脚本时都加载文件,对吗?我有一些建议:
you could load in only part of the CSV file using pandas.read_csv(..., nrows=1000) to only load the top bit of the table, while you're doing the development use ipython for an interactive session, such that you keep the pandas table in memory as you edit and reload your script. convert the csv to an HDF5 table updated use DataFrame.to_feather() and pd.read_feather() to store data in the R-compatible feather binary format that is super fast (in my hands, slightly faster than pandas.to_pickle() on numeric data and much faster on string data).
您可能还会对stackoverflow上的答案感兴趣。
泡菜很好!
import pandas as pd
df.to_pickle('123.pkl') #to save the dataframe, df to 123.pkl
df1 = pd.read_pickle('123.pkl') #to load 123.pkl back to the dataframe df
推荐文章
- 数据类vs类型。NamedTuple主要用例
- 如何从macOS完全卸载蟒蛇
- 是否有可能键入提示一个lambda函数?
- 'dict'对象没有has_key属性
- 使用Pandas groupby连接来自几行的字符串
- Pandas:给定列的数据帧行之和
- 如何避免在为Python项目构建Docker映像时重新安装包?
- 如何激活蟒蛇环境
- 省略[…]意思是在一个列表里?
- 将数据帧行按向量按特定顺序排序
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件