2014-05-13 44 views
1

我想連接2個熊貓數據幀,每個時間序列索引可能會重疊,但也可能與列鍵可能重疊。沿時間序列索引連接熊貓數據幀而不復制列

例如:

old_close         new_close 
      1TM ABL ...     ABL ANG ... 
Date        Date 
2009-06-05 100  564    1990-06-08 120 2533 
2009-06-04 102  585    1990-06-05 121 2531 
2009-06-03 101  532    1990-06-04 123 2520 
2009-06-02 99  540    1990-06-03 122 2519 
2009-06-01 99  542    1990-06-02 121 2521 
... 

我要合併old_close和new_close形成一個新的數據幀,其中包括在兩個DataFrames的所有數據,但不包括在這兩個指數的所有重複值。

到目前爲止,我這樣做:

merged_close = pd.concat([old_close, new_close], axis=1) 

但這會導致重複列(行時沿軸0)和多指標。

回答

2

假設,你要 '排除在這兩個指數都重複值',這應該工作

unique_indices = np.setdiff1d(np.unioin1d(old_close.index.to_list(), new_close.index.to_list()), 
           np.intersect1d(old_close.index.to_list(), new_close.index.to_list())) 
merged_close = pd.concat([old_close, new_close]).ix[unique_indices] 

編輯:更新了唯一指數計算。所有重複索引現在被丟棄

+0

謝謝,但結果數據框仍然包含日期索引上的重複項。這怎麼可能? – nswart

+0

我的不好,現在更新了答案 – user1827356

0

panda documentation

concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, 
     keys=None, levels=None, names=None, verify_integrity=False) 

verify_integrity: boolean, default False. Check whether the new concatenated axis contains duplicates. This can be very expensive relative to the actual data concatenation

你試過設置,參數設置爲true?

編輯:

對不起,verify_integrity只是引發錯誤,如果有重複。 無論如何,你可以嘗試看看drop_duplicates()函數。

PS:也來看看這個問題:

python pandas remove duplicate columns

+0

我收到一個'ValueError:索引有重疊的值:' – nswart