4

DatetimeIndex在比较两个具有不同长度的 's时,我遇到了一个问题assert,如下所示:

In [1]: idx1 = pd.date_range('2010-01-01','2010-12-31',freq='D')

In [2]: idx2 = pd.date_range('2010-01-01','2010-11-01',freq='D')

In [3]: assert (idx1 == idx2).all()

我得到错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-17-ad2cfd6d11c2> in <module>()
----> 1 assert (idx1 == idx2).all()

/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.10.1.dev_dcd9df7-py2.7-macosx-10.8-x86_64.egg/pandas/tseries/index.pyc in wrapper(self, other)
     75         result = func(other)
     76 
---> 77         return result.view(np.ndarray)
     78 
     79     return wrapper

AttributeError: 'NotImplementedType' object has no attribute 'view'

如果这还没有实现,那很好,但是有一些熊猫方法可以做到这一点吗?

注意: 我已经成功使用了以下内容:

In [3]: assert list(idx1) == list(idx2)

因此,以下方法也有效:

In [3]: assert list(df.index) == list(testindex)

但我想知道是否有更pandas-ish的方式来做到这一点。

4

2 回答 2

5
In [1]: import pandas as pd

In [2]: idx1 = pd.date_range('2010-01-01','2010-12-31',freq='D')

In [3]: idx2 = pd.date_range('2010-01-01','2010-11-01',freq='D')

In [4]: idx3 = pd.date_range('2010-01-01','2010-12-31',freq='D')

In [5]: help(idx1.equals)
Help on method equals in module pandas.tseries.index:

equals(self, other) method of pandas.tseries.index.DatetimeIndex instance
    Determines if two Index objects contain the same elements.


In [6]: print(idx1.equals(idx2))
False

In [7]: print(idx1.equals(idx3))
True
于 2013-01-01T16:31:08.917 回答
0

您现在有了pandas.Index.Difference,它可能适合您的需求。

就这么简单:

idx_common = idx1.difference(idx2)
于 2017-05-09T14:44:22.863 回答