【发布时间】:2019-04-10 04:56:38
【问题描述】:
我正在构建一个工具,以帮助每周自动审查来自多个实验室设置的数据。每天都会生成一个制表符分隔的文本文件。每行代表每 2 秒获取的数据,因此有 43200 行和许多列(每个文件为 75mb)
我正在使用 pandas.readcsv 加载七个文本文件,并且只将我需要的三列提取到 pandas 数据框中。这比我想要的慢,但可以接受。然后,我使用 Plotly 离线绘制数据以查看交互式绘图。这是一项设置为每周运行一次的计划任务。
数据是根据日期和时间绘制的。通常,测试设置会暂时离线,并且数据中会出现空白。不幸的是,当绘制此图时,所有数据都通过线连接,即使测试离线数小时或数天。
防止这种情况的唯一方法是在两个日期之间插入一行日期,其中包含实际数据和所有缺失数据的 NaN。我已经很容易地为丢失的数据文件实现了这一点,但是我想将这一点概括为大于某个时间段的数据间隙。我想出了一个似乎可行但确实很慢的解决方案:
# alldata is a pandas dataframe with 302,000 rows and 4 columns
# one datetime column and three float32 columns
alldata_gaps = pandas.DataFrame() #new dataframe with gaps in it
#iterate over all rows. If the datetime difference between
#two consecutive rows is more than one minute, insert a gap row.
for i in range(0, len(alldata)):
alldata_gaps = alldata_gaps.append(alldata.iloc[i])
if alldata.iloc[i+1, 0]-alldata.iloc[i,0] > datetime.timedelta(minutes=1):
Series = pandas.Series({'datetime' : alldata.iloc[i,0]
+datetime.timedelta(seconds=3)})
alldata_gaps = alldata_gaps.append(Series)
print(Series)
有没有人建议我如何加快此操作,以免花费如此令人讨厌的长时间?
Here's a dropbox link to an example data file with only 100 lines
Here's a link to my current script without adding the gap rows
【问题讨论】:
-
您能否提供一个简短示例来说明您的数据是什么样的,以便其他人可以为您的数据制定解决方案?
-
DFs 不可行扩展:追加一行需要线性时间和空间。因此,如果您在循环中追加 n 行,则循环会花费您 O(n^2) 的时间,这会迅速爆发。
标签: python pandas performance dataframe