我需要在 pandas.Dataframe 中保留记录日志(传感器数据),但我只需要保留最近 24 小时的记录。每秒都有一个新记录到达。
记录的格式为:
{'Date': ..., 'Sensor1': 10, 'Sensor2': 12, ...}
其中“日期”也应该是 DataFrame 的索引。
当然可以使用:
df = df.append( newRecord )
df.drop( df[df.Date < datetime.now() - timedelta( hours=24 )].index] )
但我觉得它很丑。
这样做最有效、最像 Pandas 的方法是什么?
最佳答案
我认为您可以将 subset
与 boolean indexing 一起使用用于删除行,但这不是最快的方法。您可以将 Date
列设置为 index
,然后按 end
时间截断 DataFrame
。
import pandas as pd
import datetime as datetime
#create testing DataFrame
def format_time():
t = datetime.datetime.now()
s = t.strftime('%Y-%m-%d %H:%M:%S')
return pd.to_datetime(s)
start = format_time()
print start
2016-03-13 09:12:44
N = 85000
df = pd.DataFrame({'Date': pd.Series(pd.date_range(start - pd.Timedelta(days=1, minutes=20) , periods=N, freq='s')), 'a': range(N)})
print df.head()
Date a
0 2016-03-12 08:52:44 0
1 2016-03-12 08:52:45 1
2 2016-03-12 08:52:46 2
3 2016-03-12 08:52:47 3
4 2016-03-12 08:52:48 4
#set index from column Date
df = df.set_index('Date')
#print df
#find chopping time
end = start - pd.Timedelta(days=1)
print end
2016-03-12 09:12:44
#boolean indexing
df1 = df[(df.index >= end ) & (df.index <= start)]
#chopping method
df2 = df[end:]
#test equality
print df1.equals(df2)
True
测试:
In [87]: %timeit df[(df.index >= end ) & (df.index <= start)]
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached
1000 loops, best of 3: 1.75 ms per loop
In [88]: %timeit df[end:]
The slowest run took 6.84 times longer than the fastest. This could mean that an intermediate result is being cached
10000 loops, best of 3: 120 µs per loop
关于python - 在 pandas.DataFrame 中保留最后 24 小时的日志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35959675/