這是我的第一篇文章,所以請溫柔。我在全球範圍內搜索尋找解決方案,但我還沒有找到解決方案。我試圖解決的問題如下:Pandas.SHIFT多索引框架時間依賴
- 我有一個數據集,包含500.000+個樣本,每個樣本有6個特徵。
- 我已經把這個數據集在multiindexed熊貓數據幀
我的數據幀的第一個層次是時間序列索引,第二個層次是ID。它看起來如下
Time id
2017-03-07 10:06:49.963241984 122.0 -7.024347
136.0 -11.664985
243.0 1.716150
2017-03-07 10:06:50.003462400 122.0 -7.025922
136.0 -11.671526
每個時間戳,可以看到一些對象,並用標記'id'標記。對於我的應用程序,我想通過包含5秒前發生的信息 添加時間依賴關係,即在此示例中的時間戳10:06:45。 但是,重要的是,我只想添加此信息,如果在該時間戳對象已經存在(所以如果ID是相等的)。
我想使用的功能dataframe.shift,如前所述here和,我想這樣做每升一級,從而在How do you shift Pandas DataFrame with a multiindex?
我的問題由用戶Unutbu表示如下: 如何追加向原始數據框X添加額外的列,並提供關於這些對象是5年前的內容的信息。我會期望像下面的東西
X['x_location_shifted'] = X.groupby(level=1)['x_location'].shift(5*rate)
與率是25Hz,即。我們移動了125個「DateTimeIndices」,但是,只有在該時間戳處存在具有id ='...'的對象時。
編輯: 時間戳不是100%同步的,所以時間間隔並不總是正好等於0.04。以前,我使用np.argmin(np.abs(time-index))來找到最接近郵票的索引。
例如,在我的設置中,在時間戳2017-03-07 10:36:03.605008640有一個id == 175和location_x = 54.323的對象。
id = 175
X.ix['2017-03-07 10:36:03.605008640', id] = 54.323
在時間戳2017年3月7日10:36:08.604962560 .....此目的使用id = 175具有location_x = 67.165955
id = 175
old_time = pd.to_datetime('2017-03-07 10:36:03.605008640')
new_time = old_time + pd.Timedelta('5 seconds')
# Finding the new value of location
X.ix[np.argmin(np.abs(new_time - X.index.get_level_values(0))), id]
所以,最後,在時間步10: 36:08我想添加timestamp的信息10:36:03如果對象已經存在於該時間戳。
編輯2: 在嘗試MaartenFabré的解決方案後,我想出了自己的實現,您可以在下面找到它。如果任何人都可以向我展示更加pythonic的方式來做到這一點,請讓我知道。
for current_time in X.index.get_level_values(0)[125:]:
#only do if there are objects at current time
if len(X.ix[current_time].index):
# Calculate past time
past_time = current_time - pd.Timedelta('5 seconds')
# Find index in X.index that is closest to this past time
past_time_index = np.argmin(np.abs(past_time-X.index.get_level_values(0)))
# translate the index back to a label
past_time = X.index[past_time_index][0]
# in that timestep, cycle the objects
for obj_id in X.ix[current_time].index:
# Try looking for the value box_center.x of obj obj_id 5s ago
try:
X.ix[(current_time, obj_id), 'box_center.x.shifted'] = X.ix[(past_time, obj_id), 'box_center.x']
X.ix[(current_time, obj_id), 'box_center.y.shifted'] = X.ix[(past_time, obj_id), 'box_center.y']
X.ix[(current_time, obj_id), 'relative_velocity.x.shifted'] = X.ix[(past_time, obj_id), 'relative_velocity.x']
X.ix[(current_time, obj_id), 'relative_velocity.y.shifted'] = X.ix[(past_time, obj_id), 'relative_velocity.y']
# If the key doesnt exist, the object doesn't exist, ergo the field should be np.nan
except KeyError:
X.ix[(current_time, obj_id), 'box_center.x.shift'] = np.nan
print('Timestep {}'.format(current_time))
如果沒有足夠的信息,請告訴我,我可以添加它:)
歡呼和感謝!
5s差異的確切程度如何,因爲在這裏我們看到的示例數據中數據之間只有0.04s。你能否提供一些5s差距適用的樣本數據? –
我加了要求的信息 –