【问题标题】:Converting a DateTime Index value to an Index Number将 DateTime 索引值转换为索引号
【发布时间】:2019-03-03 16:31:29
【问题描述】:

如果我有一个具有日期时间索引的数据框,并且我通过使用 series.first_valid_index 获得了第一个有效索引 - 它返回第一个非 nan 的日期时间,但这是我正在寻找的:

有没有办法获取日期时间值对应的索引号。例如,它返回 2018-07-16 但我想知道这是数据帧的第 18 行?

如果没有,有没有办法计算从数据帧开头到该索引值的行数?

【问题讨论】:

    标签: python pandas numpy datetime dataframe


    【解决方案1】:

    TLDR:如果您要寻求一种将给定索引值(在本例中为 DatetimeIndex)映射到其等效整数的方法,您是在问对于get_loc,如果您只想从系列中查找整数索引,请使用argmax 和底层numpy 数组。

    设置

    np.random.seed(3483203)
    
    df = pd.DataFrame(
        np.random.choice([0, np.nan], 5),
        index=pd.date_range(start='2018-01-01', freq='1D', periods=5)
    )
    

                  0
    2018-01-01  NaN
    2018-01-02  NaN
    2018-01-03  0.0
    2018-01-04  NaN
    2018-01-05  NaN
    

    在这里使用pandas.Index.get_loc,这是一个通用函数,用于返回给定标签的整数索引:

    >>> idx = df[0].first_valid_index()
    >>> idx
    Timestamp('2018-01-03 00:00:00', freq='D')
    >>> df.index.get_loc(idx)
    2
    

    如果您想完全避免找到datetime 索引,您可以在底层numpy 数组上使用argmax

    >>> np.argmax(~np.isnan(df[0].values))
    2
    

    【讨论】:

    • 是的,我试图使用 get_loc 但我的语法关闭了。这成功了。谢谢!
    • 乐于助人!就像我上面提到的,get_loc 是在给定日期时间索引的情况下找到整数索引的正确方法。但是,如果您想跳过该中间步骤,请在我的回答末尾使用argmax 解决方案。
    【解决方案2】:

    我会尝试以下(未经测试):

    x = len(df)
    num_index = range(0,x,1)
    df =  df.reset_index()
    df = df.set_index(num_index)
    

    【讨论】:

    • 如果您仍然希望拥有初始索引(带有日期时间),请在重置索引之前使用df['date'] = df.index
    【解决方案3】:

    您可以将np.arwherenp.isnanpd.notnull 一起使用:

    np.argwhere(~np.isnan(s)).flat[0]
    # or:
    # np.argwhere(pd.notnull(s)).flat[0]
    

    鉴于系列:

    >>> s
    2018-09-27    NaN
    2018-09-28    NaN
    2018-09-29    5.0
    2018-09-30    5.0
    2018-10-01    NaN
    Freq: D, dtype: float64
    

    你得到:

    >>> np.argwhere(~np.isnan(s)).flat[0]
    2
    

    或者,只需重置索引并获取first_valid_index

    >>> s.reset_index()[0].first_valid_index()
    2
    

    【讨论】:

      【解决方案4】:

      创建一个字典,键是日期时间对象,其值是您的索引。 示例代码供您参考:

      timestamp=df.iloc[0:,0].tolist()
      timestamp_dict={}
      number=0
      for time in timestamp:
          timestamp_dict[time]=number
          number+=1
      

      希望对你有所帮助。

      【讨论】:

        【解决方案5】:

        您只需要将“x”转换为 dataFrame,然后将 inplace 设置为 true。

        x = len(df)
        df["num_index"] = range(0, x, 1)
        df.set_index(df['num_index'], inplace=True)
        

        注意:但是这段代码会将日期索引完全替换为num_index。

        解决方案 2: 如果您想保留日期索引并用 num_index 替换索引,则应应用以下代码:

        df['Date'] = df.index
        x = len(df)
        df["num_index"] = range(0, x, 1)
        df.set_index(df['num_index'], inplace=True)
        

        现在,您将日期和数字作为索引。

        解决方案 3: 最简单的方法是重置索引

        df.reset_index(inplace=True)
        

        这将创建一个从 0 开始的索引和一个与该索引同名的列。

        【讨论】:

          猜你喜欢
          • 2018-07-09
          • 2014-02-04
          • 2021-08-28
          • 2021-06-09
          • 2016-01-25
          • 1970-01-01
          • 2021-12-17
          • 2011-04-05
          • 2019-01-31
          相关资源
          最近更新 更多