【问题标题】:'Passing list-likes to .loc in pandas'将列表喜欢传递给熊猫中的.loc
【发布时间】:2020-07-08 21:11:25
【问题描述】:

我有以下日期列表:

date_list 
DatetimeIndex(['2015-07-10', '2015-07-13', '2015-07-14', '2015-07-15',
               '2015-07-16', '2015-07-17', '2015-08-20', '2015-09-21',
               '2015-09-22', '2015-09-23']

要访问这些日期的 pandas 中的行的值,我这样做了:

df['Close'].loc[dates_list]

这会产生以下错误:

KeyError: 'Passing list-likes to .loc or [] with any missing labels is no longer supported

如何获取这些DateTtimeindex 的行值

【问题讨论】:

    标签: python python-3.x pandas datetime


    【解决方案1】:

    像魅力一样工作:

    df.loc[date_list, 'Close']
    

    测试示例,大致基于您提供的内容 - 如果与您的用例相比有什么不妥之处,请随时澄清细节:

    import pandas as pd
    
    date_list=pd.DatetimeIndex(['2015-07-10', '2015-07-13', '2015-07-14', '2015-07-15',
                   '2015-07-16', '2015-07-17', '2015-08-20', '2015-09-21',
                   '2015-09-22', '2015-09-23'])
    
    df=pd.DataFrame({'Close': list("abcdefghijklmnoprstuvwxyz"), 'dt': ['2015-07-10', '2015-07-13', '2015-07-14', '2015-07-15','2017-01-01','2017-01-03','2015-07-01','2005-09-07', '2018-02-04',
                   '2015-07-16', '2015-07-17', '2015-08-20', '2015-09-21','2019-04-06','2002-04-07','2002-05-19',
                   '2015-09-22', '2015-09-23','2020-07-07', '2020-06-08', '2018-02-01', '2000-04-04', '2001-09-09', '2008-08-03', '2008-09-01']})
    df['dt']=pd.to_datetime(df['dt'])
    df=df.set_index('dt')
    res=df.loc[date_list, 'Close']
    
    >>> res
    
    2015-07-10    a
    2015-07-13    b
    2015-07-14    c
    2015-07-15    d
    2015-07-16    j
    2015-07-17    k
    2015-08-20    l
    2015-09-21    m
    2015-09-22    r
    2015-09-23    s
    Name: Close, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 2020-06-13
      • 2021-07-21
      • 2021-03-05
      • 2021-07-18
      • 1970-01-01
      • 2020-12-24
      • 2020-11-14
      相关资源
      最近更新 更多