Skip to main content
 首页 » 编程设计

python之返回两个日期之间的数据

2024年10月24日9webabcd

我有一些代码可以解析多个 .CVS 文件,检索多个列的所有数据并将数据放入数据框(称为 dfs)中。我现在试图返回 dfs 中仅在两个日期之间的所有数据字段。

我正在尝试使用命令:

return dfs[(dfs['date'] >= startDate) & (dfs['date'] <= endDate)]  

但出现以下错误:

KeyError: 'date' 

有人可以告诉我我做错了什么吗? 请参阅下面的代码:

def getTimeseriesData(path,column_num,startDate,endDate): 
    colNames = ['date'] 
    dfs = [] 
 
    allfiles = glob.glob(os.path.join(path, "*.csv")) 
    for fname in allfiles: 
 
        name = os.path.splitext(fname)[0] 
        name = os.path.split(name)[1] 
        colNames.append(name) 
 
        df = pd.read_csv(fname, header=None, usecols=[0, column_num,4,5],  
                        parse_dates=[0], dayfirst=True, 
                        index_col=[0], names=['date', name+'_LAST',name+'_VOLUME',name+'_MKTCAP']) 
 
        df = df.groupby(level=0).agg('mean') 
 
        dfs.append(df)         
 
    dfs = pd.concat(dfs, axis=1) 
 
    return dfs[(dfs['date'] >= startDate) & (dfs['date'] <= endDate)] #<<--I think this is the problem 

dfs 的头部(我想从中返回两个日期之间的数据(比如 2001-01-03 和 2001-01-05 之间)看起来像这样:

            BBG.XLON.BTA.S_LAST  BBG.XLON.BTA.S_VOLUME  BBG.XLON.BTA.S_MKTCAP  \ 
date                                                                             
2001-01-02                  572               26605510               37494.60    
2001-01-03                  560               24715470               36708.00    
2001-01-04                  613               52781855               40182.15    
2001-01-05                  630               56600152               41296.50    
2001-01-08                  633               41014402               41493.15    
 
            BBG.XLON.VOD.S_LAST  BBG.XLON.VOD.S_VOLUME  BBG.XLON.VOD.S_MKTCAP   
date                                                                            
2001-01-02                  NaN                    NaN                    NaN   
2001-01-03               225.00              444328736            145216.0020   
2001-01-04               239.00              488568000            154251.6643   
2001-01-05               242.25              237936704            156349.2288   
2001-01-08               227.75              658059776            146990.8642  

请您参考如下方法:

此处 date 是您的索引名称,而不是列名称:

改变:

return dfs[(dfs['date'] >= startDate) & (dfs['date'] <= endDate)]  

进入:

return dfs[(dfs.index >= startDate) & (dfs.index <= endDate)]