我有一部分测量时间,仪器时间配置错误,需要更正。
所以我试图将我的数据帧的一部分偏移或移位2小时,但我似乎无法使用以下代码:
dfs['2015-03-23 10:45:00':'2015-03-23 13:15:00'].shift(freq=datetime.timedelta(hours=2))
我不知道是否可以这么做。
希望有人理解我的问题:)
>>> dfs.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 11979 entries, 2015-03-23 10:45:05 to 2015-03-23 16:19:32
Data columns (total 11 columns):
CH-1[V] 11979 non-null float64
CH-2[V] 11979 non-null float64
CH-3[V] 11979 non-null float64
CH-4[V] 11979 non-null float64
CH-5[V] 11979 non-null float64
CH-6[V] 11979 non-null float64
CH-7[V] 11979 non-null float64
CH-9[C] 11979 non-null float64
CH-10[C] 11979 non-null float64
Event 11979 non-null int64
Unnamed: 11 0 non-null float64
dtypes: float64(10), int64(1)
memory usage: 1.1 MB
答案 0 :(得分:1)
Pandas Indexes不可变,因此我们无法就地更改索引。 但是,我们可以将索引设为DataFrame列,修改列,然后重置索引:
import numpy as np
import pandas as pd
# Suppose this is your `dfs`:
index = pd.date_range('2015-03-23 10:45:05', '2015-03-23 16:19:32', freq='T')
N = len(index)
dfs = pd.DataFrame(np.arange(N), index=index)
# move the index into a column
dfs = dfs.reset_index()
mask = (index >= '2015-03-23 10:45:00') & (index <= '2015-03-23 13:15:00')
# shift the masked values in the column
dfs.loc[mask, 'index'] += pd.Timedelta(hours=2)
# use the index column as the index
dfs = dfs.set_index(['index'])
这表明索引已经移动了2个小时:
In [124]: dfs.iloc[np.where(mask)[0].max()-1:].head(5)
Out[124]:
0
index
2015-03-23 15:13:05 148
2015-03-23 15:14:05 149 <-- shifted by 2 hours
2015-03-23 13:15:05 150 <-- unchanged
2015-03-23 13:16:05 151
2015-03-23 13:17:05 152