保持最后24小时登录Pandas.DataFram

2024-10-01 00:34:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要把记录(传感器数据)记录在熊猫.数据帧但我只需要保留最后24小时。每秒钟都会有一个新记录出现。在

记录格式为:

{'Date': ..., 'Sensor1': 10, 'Sensor2': 12, ...}

其中'Date'也应该是数据帧的索引。在

当然,也可以使用:

df = df.append( newRecord ) df.drop( df[df.Date < datetime.now() - timedelta( hours=24 )].index] ) 但我觉得很难看。在

什么是最有效和熊猫式的方法?在


Tags: 数据dfdatetimedate格式记录传感器now
2条回答

我认为您可以使用subset和{a1}来删除行,但这不是最快的方法。您可以将列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
^{pr2}$

测试:

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      

每秒钟都要删除重新组织所有数据帧,这是一项代价高昂的操作:

In [6]: %timeit  df.drop(4)
10 loops, best of 3: 17.3 ms per loop

通过固定的滚动缓冲器可以避免这种情况,从而有效地存储传感器数据。索引只是一个整数,一天中每秒一个。在

^{pr2}$

这样添加样本的速度非常快:

sample={'Date': pd.Timestamp('2016-12-04 12:00:00'), 'Sensor1': .1, 'Sensor2': .2}


def indexer(t):
    return t.hour*3600+t.minute*60+t.second

def set(df,sample):
    date=sample['Date']
    index=indexer(date)
    df.iat[index,0]=sample['Date']
    df.iat[index,1]=sample['Sensor1']
    df.iat[index,2]=sample['Sensor2']


In [7]: %timeit set(df,sample)
1000 loops, best of 3: 141 µs per loop    

要将电流倒流24小时,只需执行以下操作:

dfnow=df.set_index(df['Date']).sort_index().copy()

现在时间就是索引。在

相关问题 更多 >