【问题标题】:Pandas: How do I get the key (index) of the first and last row of a dataframePandas:如何获取数据帧第一行和最后一行的键(索引)
【发布时间】:2018-01-01 09:42:49
【问题描述】:

我有一个带有日期时间索引和一个字段“myfield”的数据框 (df)

我想找出数据框的第一个和最后一个日期时间。

我可以像这样访问第一个和最后一个数据框元素:

df.iloc[0]
df.iloc[-1]

对于df.iloc[0],我得到了结果:

我的字段我的字段内容

名称:2017-07-24 00:00:00,数据类型:float

如何访问该行的日期时间?

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    您可以使用 select index by [0] 或 [-1]:

    df = pd.DataFrame({'myfield':[1,4,5]}, index=pd.date_range('2015-01-01', periods=3))
    print (df)
                myfield
    2015-01-01        1
    2015-01-02        4
    2015-01-03        5
    
    print (df.iloc[-1])
    myfield    5
    Name: 2015-01-03 00:00:00, dtype: int64
    
    print (df.index[0])
    2015-01-01 00:00:00
    
    print (df.index[-1])
    2015-01-03 00:00:00
    

    【讨论】:

      【解决方案2】:

      jezrael's answer 是完美的。只是为了提供一个替代方案,如果你坚持使用loc,那么你应该先reset_index。

      import pandas as pd
      
      df = pd.DataFrame({'myfield': [1, 4, 5]}, index=pd.date_range('2015-01-01', periods=3))
      df = df.reset_index()
      print df['index'].iloc[0]
      print df['index'].iloc[-1]
      

      【讨论】:

      • 如果索引是日期时间则可能不会
      【解决方案3】:

      如果您使用的是 pandas 1.1.4 或更高版本,则可以使用“name”属性。

      import pandas as pd
      
      df = pd.DataFrame({'myfield': [1, 4, 5]}, index=pd.date_range('2015-01-01', periods=3))
      df = df.reset_index()
      print("Index value: ", df.iloc[-1].name) #pandas-series
      #Convert to python datetime
      print("Index datetime: ", df.iloc[-1].name.to_pydatetime()) 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-09-29
        • 2019-05-24
        • 2020-07-26
        • 2022-01-13
        • 1970-01-01
        • 2014-11-10
        • 1970-01-01
        • 2023-04-09
        相关资源
        最近更新 更多