【问题标题】:python: what is wrong with my date index?python:我的日期索引有什么问题?
【发布时间】:2020-03-04 03:11:34
【问题描述】:

我有一个使用日期作为索引的数据框。虽然可以从 series.index 中读取索引值,但是无法获取到对应的记录。

series = pd.DataFrame([[datetime.date(2019,1,1), 'A', 4], [datetime.date(2019,1,2), 'B', 6]], columns = ('Date', 'Index', 'Value'))
series2 = series.pivot(index='Date', columns='Index', values='Value')
index = series2.index[0]

到目前为止,一切正常。 但是这行代码失败了:

row = series[index]

错误信息是

KeyError: datetime.date(2019, 1, 1)

为什么会失败,我该如何解决?

【问题讨论】:

    标签: python pandas date dataframe indexing


    【解决方案1】:

    使用Series.loc 进行选择,但在series2 中,因为在series 中是RangeIndex,而不是日期:

    row = series2.loc[index]
    print (row)
    Index
    A    4.0
    B    NaN
    Name: 2019-01-01, dtype: float64
    

    详情

    print (series)
             Date Index  Value
    0  2019-01-01     A      4
    1  2019-01-02     B      6
    
    print (series.index)
    RangeIndex(start=0, stop=2, step=1)
    
    print (series2)
    Index         A    B
    Date                
    2019-01-01  4.0  NaN
    2019-01-02  NaN  6.0
    

    【讨论】:

      【解决方案2】:

      在您的三行之后添加此部分: series.set_index('Date', inplace=True)

      所以,整件事是:

      import pandas as pd
      import datetime
      
      series = pd.DataFrame([[datetime.date(2019,1,1), 'A', 4], 
          [datetime.date(2019,1,2), 'B', 6]], 
          columns = ('Date', 'Index', 'Value'))
      series2 = series.pivot(index='Date', columns='Index', 
          values='Value')
      index = series2.index[0]
      series.set_index('Date', inplace=True) # this part was added
      series.loc[index]
      
      Out[57]: 
      Index    A
      Value    4
      Name: 2019-01-01, dtype: object
      

      【讨论】:

      • 在我的情况下不需要 set_index, loc 就足够了。不过,坦克可以跳进去!
      猜你喜欢
      • 1970-01-01
      • 2023-03-04
      • 2017-04-16
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 2018-07-31
      相关资源
      最近更新 更多