2017-02-20 75 views
0

I'va實際上2數據幀:熊貓尋找時間作爲索引而忽略日期

  1. 首先一個包含與日期的一些信息/時間
  2. 第二個包含與日期的其他信息/時間

我需要通過使用最近的時間作爲關鍵2數據幀結合(忽略日期)

我需要與在所述第一數據幀的給定時間,以找到最近的時間索引(或值)在第二個數據幀

我希望你明白

編輯:

從CSV數據幀1:

date;index 
01/01/90 00:00:00;2 
01/01/90 00:00:30;9 

從CSV數據幀2:

date;value 
02/02/00 00:00:02;300 

需要:

date;value;index 
02/02/00 00:00:02;300;2 
+1

你能與所需的輸出添加一些樣本數據? – jezrael

回答

1

您可以使用reindexmethod='nearest'

#new indexes with same dates, but different times 
df1.index = pd.to_datetime(df1['date'].dt.strftime('%H:%M:%S')) 
df2.index = pd.to_datetime(df2['date'].dt.strftime('%H:%M:%S')) 
print (df1) 
            date index 
date           
2017-02-20 00:00:00 1990-01-01 00:00:00  2 
2017-02-20 00:30:00 1990-01-01 00:00:30  9 

print (df2) 
            date value 
date           
2017-02-20 00:02:00 2000-02-02 00:00:02 300 

df3 = df1.reindex(df2.index, method='nearest') 
#add values from df2 
df = pd.concat([df3.drop('date', axis=1), df2], axis=1).reset_index(drop=True) 
print (df) 
    index    date value 
0  2 2000-02-02 00:00:02 300 
+0

如果我將02/02/00 00:00:04; 300添加到csv,它將成爲索引2 – Timo

+0

爲什麼在您的索引中省略%H? – Timo

+0

是的,對不起。你是對的。 – jezrael

相關問題