现在,每次运行脚本时,我都会导入一个相当大的CSV作为数据框架。是否有一个好的解决方案来保持数据帧在运行之间不断可用,这样我就不必花费所有的时间等待脚本运行?
当前回答
您可以使用羽毛格式的文件。它非常快。
df.to_feather('filename.ft')
其他回答
泡菜很好!
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
如果我理解正确的话,你已经在使用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上的答案感兴趣。
Numpy文件格式对于数字数据来说非常快
我更喜欢使用numpy文件,因为它们快速且易于使用。 下面是一个简单的基准测试,用于保存和加载一个包含100万个点的1列数据框架。
import numpy as np
import pandas as pd
num_dict = {'voltage': np.random.rand(1000000)}
num_df = pd.DataFrame(num_dict)
使用ipython的%%timeit魔法函数
%%timeit
with open('num.npy', 'wb') as np_file:
np.save(np_file, num_df)
输出为
100 loops, best of 3: 5.97 ms per loop
将数据加载回数据框架
%%timeit
with open('num.npy', 'rb') as np_file:
data = np.load(np_file)
data_df = pd.DataFrame(data)
输出为
100 loops, best of 3: 5.12 ms per loop
不坏!
CONS
如果您使用python 2保存numpy文件,然后尝试使用python 3打开,则会出现问题(反之亦然)。
您可以使用羽毛格式的文件。它非常快。
df.to_feather('filename.ft')
to_pickle()的另一个非常新鲜的测试。
我总共有25个.csv文件要处理,最终的数据框架由大约2M项组成。
(注意:除了加载.csv文件,我还操作了一些数据,并通过新列扩展数据帧。)
浏览所有25个.csv文件并创建dataframe大约需要14秒。
从pkl文件加载整个数据帧的时间不到1秒
推荐文章
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象
- 用Python构建最小的插件架构
- model.eval()在pytorch中做什么?
- Tensorflow 2.0:模块“Tensorflow”没有属性“Session”
- 从环境文件中读入环境变量
- 在OSX 10.11中安装Scrapy时,“OSError: [Errno 1]操作不允许”(El Capitan)(系统完整性保护)
- 如何删除熊猫数据帧的最后一行数据