代码之家  ›  专栏  ›  技术社区  ›  Kernel

TypeError:Index.reindex()收到意外的关键字参数fill_value'

  •  0
  • Kernel  · 技术社区  · 4 月前

    我试图通过将缺失日期与未缺失日期列表进行比较来获取缺失日期的索引,如下所示:

    a = pd.DatetimeIndex(["2000", "2001", "2002", "2003",
                          "2004", "2005", "2009", "2010"])
    b = pd.DatetimeIndex(["2000", "2001", "2002", "2003",
                          "2004", "2005", "2006", "2007",
                          "2008", "2009", "2010"])
    a.reindex(b)
    

    我得到了以下信息

    (DatetimeIndex(['2000-01-01', '2001-01-01', '2002-01-01', '2003-01-01',
                    '2004-01-01', '2005-01-01', '2006-01-01', '2007-01-01',
                    '2008-01-01', '2009-01-01', '2010-01-01'],
                   dtype='datetime64[ns]', freq=None),
     array([ 0,  1,  2,  3,  4,  5, -1, -1, -1,  6,  7]))
    

    我试图用以下方式替换所有缺失的值,即Nan的-1 a.reindex(b, fill_value=np.NAN) 但我得到了以下错误 TypeError: Index.reindex() got an unexpected keyword argument ‘fill_value’

    根据 pandas documentation fill_vue是reindex的参数之一。 有什么想法吗?

    2 回复  |  直到 4 月前
        1
  •  1
  •   wjandrea senderle    4 月前

    首先,你必须做到:

    newIndex, indexer = a.reindex(b)
    

    reindex 返回两件事。您只需要/想要获取索引器。

    现在你可以得到你想要的:

    indexerWithNan = np.where(indexer == -1, np.nan, indexer)
    

    即:

    [ 0.  1.  2.  3.  4.  5. nan nan nan  6.  7.]
    

    为什么你最初的代码错了?这个 reindex() 方法不支持 fill_value 参数 pandas.Index 对象,因为它为 pandas.Series pandas.DataFrame .

        2
  •  1
  •   mozway    4 月前

    如果你只是想知道哪些值 b 缺少 a 使用 Index.isin :

    ~b.isin(a)
    

    输出:

    array([False, False, False, False, False, False,  True,  True,  True,
           False, False])
    

    如果你想得到缺失的值:

    b[~b.isin(a)]
    

    输出:

    DatetimeIndex(['2006-01-01', '2007-01-01', '2008-01-01'], dtype='datetime64[ns]', freq=None)
    

    对于指数:

    np.where(~b.isin(a))[0]
    

    输出: array([6, 7, 8])