2014-05-13 42 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