【问题标题】:How to get the index value in a dataframe by comparing date with a datetime object in that dataframe?如何通过将日期与该数据框中的日期时间对象进行比较来获取数据框中的索引值?
【发布时间】:2019-01-31 08:25:55
【问题描述】:

我有一个如下所示的数据框。我想通过检查日期来获取索引值。例如,如果日期是 2018-04-05,我需要将索引值设为 3。有人可以告诉我该怎么做吗?

       close                      date     high      low     open   volume
0    1536.95 2018-04-02 09:15:00+05:30  1545.00  1509.40  1509.40   420761   
1    1554.80 2018-04-03 09:15:00+05:30  1562.00  1534.00  1534.00   201412   
2    1530.00 2018-04-04 09:15:00+05:30  1576.85  1525.85  1554.00   171614   
3    1552.35 2018-04-05 09:15:00+05:30  1559.70  1536.90  1551.40   198303   
4    1553.25 2018-04-06 09:15:00+05:30  1560.95  1542.85  1558.00   119196   
5    1541.30 2018-04-09 09:15:00+05:30  1559.15  1535.65  1552.90   175732   
6    1539.15 2018-04-10 09:15:00+05:30  1555.90  1531.45  1555.90   112086   
7    1533.55 2018-04-11 09:15:00+05:30  1543.50  1520.10  1531.90   319761   

【问题讨论】:

    标签: python pandas date object dataframe


    【解决方案1】:

    我的做法是

    df.loc[df["date"] == "2018-04-05"].index[0]
    # outputs
    (3, 1552.3499999999999)
    

    df.loc[df["date"] == "2018-04-05"].index.values
    # outputs
    array([(3, 1552.35)], dtype=object)
    

    在这两种情况下,您都可以选择第一个元素

    df.loc[df["close"] == "2018-04-05"].index[0][0] #gives 3

    df.loc[df["close"] == "2018-04-05"].index.values[0][0] #gives 3

    【讨论】:

      【解决方案2】:

      您还可以执行以下操作:

      a = [1,2,3,4,5]
      b = [1,0.4,0.3,0.5,0.2]
      
      df = pd.DataFrame({'a':a , 'b': b})
      
      df.loc[df['a'] == 1].index.item()
      

      输出是:

      df is:
      
          a    b
      0  1  1.0
      1  2  0.4
      2  3  0.3
      3  4  0.5
      4  5  0.2
      
      
      index:
       0
      

      【讨论】:

        【解决方案3】:

        您可以使用datetimenormalize 属性将时间部分归零,这样您就可以直接将datetime 与字符串进行比较

        import pandas as pd
        date= '2018-04-05'
        #df['date'] = pd.to_datetime(df.date)
        
        df[df.date.dt.normalize() == date].index.values
        #array([3], dtype=int64)
        

        【讨论】:

        • 非常感谢!这对我帮助很大。谢谢。
        猜你喜欢
        • 2019-10-14
        • 2019-12-17
        • 2019-03-12
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 2021-11-05
        • 2022-08-07
        • 1970-01-01
        相关资源
        最近更新 更多