现在,每次运行脚本时,我都会导入一个相当大的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上的答案感兴趣。

其他回答

您可以使用羽毛格式的文件。它非常快。

df.to_feather('filename.ft')

Pandas DataFrame有to_pickle函数,这对于保存DataFrame非常有用:

import pandas as pd

a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

a.to_pickle('my_file.pkl')

b = pd.read_pickle('my_file.pkl')
print b
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

to_pickle()的另一个非常新鲜的测试。

我总共有25个.csv文件要处理,最终的数据框架由大约2M项组成。

(注意:除了加载.csv文件,我还操作了一些数据,并通过新列扩展数据帧。)

浏览所有25个.csv文件并创建dataframe大约需要14秒。

从pkl文件加载整个数据帧的时间不到1秒

泡菜很好!

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

如前所述,有不同的选项和文件格式(HDF5, JSON, CSV, parquet, SQL)来存储数据帧。然而,pickle不是一级公民(取决于你的设置),因为:

泡菜是一个潜在的安全隐患。形成pickle的Python文档:

警告pickle模块不安全 恶意构造的数据。对象接收的数据永远不能解pickle 不受信任或未经身份验证的源。

泡菜很慢。找到这里和这里的基准。

根据您的设置/使用情况,这两个限制都不适用,但我不建议将pickle作为pandas数据帧的默认持久性。