2016-11-09 40 views
5

假設我有兩個dataframes:大熊貓:另一系列的時間指數的時間間隔(即時間範圍除外)內刪除所有行

#df1 
time 
2016-09-12 13:00:00.017 1.0 
2016-09-12 13:00:03.233 1.0 
2016-09-12 13:00:10.256 1.0 
2016-09-12 13:00:19.605 1.0 

#df2 
time 
2016-09-12 13:00:00.017 1.0 
2016-09-12 13:00:00.233 0.0 
2016-09-12 13:00:01.016 1.0 
2016-09-12 13:00:01.505 0.0 
2016-09-12 13:00:06.017 1.0 
2016-09-12 13:00:07.233 0.0 
2016-09-12 13:00:08.256 1.0 
2016-09-12 13:00:19.705 0.0 

我想刪除df2是高達1秒所有行在df1時間指數,所以產生:

#result 
time 
2016-09-12 13:00:01.505 0.0 
2016-09-12 13:00:06.017 1.0 
2016-09-12 13:00:07.233 0.0 
2016-09-12 13:00:08.256 1.0 

什麼是最有效的方式做到這一點?我沒有看到API中的時間範圍排除有用。

回答

11

您可以使用pd.merge_asof這是一個新的開始納入與0.19.0和也接受公差參數匹配+/-在指定時間間隔的量。

# Assuming time to be set as the index axis for both df's 
df1.reset_index(inplace=True) 
df2.reset_index(inplace=True) 

df2.loc[pd.merge_asof(df2, df1, on='time', tolerance=pd.Timedelta('1s')).isnull().any(1)] 

enter image description here

注意,默認匹配在向後方向,這意味着選擇發生在正確的數據幀中的最後一行(df1),其"on"鍵(這是"time")進行小於或等於左邊的(df2)鍵。因此,tolerance參數僅在此方向上延伸(後向),導致-匹配範圍。

兼得向前以及落後查找可能的,這0.20.0開始可以通過使用direction='nearest'論證,並把它放置在函數調用來實現。由於這個原因,tolerance也得到了擴展,導致帶寬的匹配範圍爲+/-

+1

打我吧... – piRSquared

+2

haha​​ ..記得有關@ MaxU的評論幾天後它的寬容參數。 –

1

一種方式做到這一點是通過時間索引查找(假設兩個時間列索引):

td = pd.to_timedelta(1, unit='s') 
df2.apply(lambda row: df1[row.name - td:row.name].size > 0, axis=1) 
4

類似想法@Nickil Maveli,但使用reindex建立一個布爾索引:

df2 = df2[df1.reindex(df2.index, method='nearest', tolerance=pd.Timedelta('1s')).isnull()] 

輸出結果:

time 
2016-09-12 13:00:01.505 0.0 
2016-09-12 13:00:06.017 1.0 
2016-09-12 13:00:07.233 0.0 
2016-09-12 13:00:08.256 1.0