我正在将多个时间序列表读入pandas dataFrame,并将它们与常见的pandas datetime索引连接在一起。记录时间序列的数据记录器不是100%准确,这使得重新采样非常烦人,因为根据时间是略高于还是低于采样间隔,它将创建NaN并开始使我的系列看起来像一条虚线。这是我的代码
def loaddata(filepaths):
t1 = time.clock()
for i in range(len(filepaths)):
xl = pd.ExcelFile(filepaths[i])
df = xl.parse(xl.sheet_names[0], header=0, index_col=2, skiprows=[0,2,3,4], parse_dates=True)
df = df.dropna(axis=1, how='all')
df = df.drop(['Decimal Year Day', 'Decimal Year Day.1', 'RECORD'], axis=1)
if i == 0:
dfs = df
else:
dfs = concat([dfs, df], axis=1)
t2 = time.clock()
print "Files loaded into dataframe in %s seconds" %(t2-t1)
files = ["London Lysimeters corrected 5min.xlsx", "London Water Balance 5min.xlsx"]
data = loaddata(files)
以下是索引的概念:
data.index
class'pandas.tseries.index.DatetimeIndex'> [2012-08-27 12:05:00.000002,...,2013-07-12 15:10:00.000004] 长度:91910,频率:无,时区:无
将指数四舍五入到最近的分钟是最快和最通用的?
答案 0 :(得分:6)
这是一个小技巧。日期时间以纳秒为单位(当被视为np.int64
时)。
所以在几纳秒内完成几分钟。
In [75]: index = pd.DatetimeIndex([ Timestamp('20120827 12:05:00.002'), Timestamp('20130101 12:05:01'), Timestamp('20130712 15:10:00'), Timestamp('20130712 15:10:00.000004') ])
In [79]: index.values
Out[79]:
array(['2012-08-27T08:05:00.002000000-0400',
'2013-01-01T07:05:01.000000000-0500',
'2013-07-12T11:10:00.000000000-0400',
'2013-07-12T11:10:00.000004000-0400'], dtype='datetime64[ns]')
In [78]: pd.DatetimeIndex(((index.asi8/(1e9*60)).round()*1e9*60).astype(np.int64)).values
Out[78]:
array(['2012-08-27T08:05:00.000000000-0400',
'2013-01-01T07:05:00.000000000-0500',
'2013-07-12T11:10:00.000000000-0400',
'2013-07-12T11:10:00.000000000-0400'], dtype='datetime64[ns]')
答案 1 :(得分:4)
Jeff提到的问题4314现已关闭,并且在pandas 0.18.0中为DatetimeIndex,Timestamp,TimedeltaIndex和Timedelta添加了round()
方法。现在我们可以做到以下几点:
In[109]: index = pd.DatetimeIndex([pd.Timestamp('20120827 12:05:00.002'), pd.Timestamp('20130101 12:05:01'), pd.Timestamp('20130712 15:10:30'), pd.Timestamp('20130712 15:10:31')])
In[110]: index.values
Out[110]:
array(['2012-08-27T12:05:00.002000000', '2013-01-01T12:05:01.000000000',
'2013-07-12T15:10:30.000000000', '2013-07-12T15:10:31.000000000'], dtype='datetime64[ns]')
In[111]: index.round('min')
Out[111]:
DatetimeIndex(['2012-08-27 12:05:00', '2013-01-01 12:05:00',
'2013-07-12 15:10:00', '2013-07-12 15:11:00'],
dtype='datetime64[ns]', freq=None)
round()
接受频率参数。列出了here的字符串别名。
答案 2 :(得分:0)
对于数据列; 使用:round_hour(df.Start_time)
def round_hour(x,tt=''):
if tt=='M':
return pd.to_datetime(((x.astype('i8')/(1e9*60)).round()*1e9*60).astype(np.int64))
elif tt=='H':
return pd.to_datetime(((x.astype('i8')/(1e9*60*60)).round()*1e9*60*60).astype(np.int64))
else:
return pd.to_datetime(((x.astype('i8')/(1e9)).round()*1e9).astype(np.int64))