python - 按数据框中的日期过滤数据

标签 python csv python-3.x pandas

下面有一些代码,将一些时间序列 csv 文件导入到数据框中,并将包含时间序列日期的列的数据框的列名称更改为“日期”,其他列设置为名称它们来自的文件。到目前为止一切都很好。现在我想读入两个预设日期之间的数据。这就是我遇到问题的地方。我无法获取仅返回从 startDate 到 endDate 的数据帧并删除其他数据行的代码。

我对此进行了各种尝试,但我无法让过滤器工作。请参阅下面我的代码的当前版本:

def getTimeseriesData4(DataPath,columnNum,startDate,endDate):
    colNames = ['date']

    path = DataPath
    filePath = path, "*.csv"
    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)

    dataframes = [pd.read_csv(fname, header=None,usecols=[0,columnNum]) for fname in allfiles]



    #this is the part where I am trying to filter out the data I do not need.  So dataframes would only have data between the startDate and the endDate
    dataframes = dataframes.set_index(['date'])
    print(dataframes.loc[startDate:endDate])



    timeseriesData = reduce(partial(pd.merge, on=0, how='outer'), dataframes)
    timeseriesData.columns=colNames

    return timeseriesData  

下面是我正在导入的数据示例

          date  BBG.BBG.AUDEUR.FX  BBG.BBG.CADEUR.FX  BBG.BBG.CHFEUR.FX  \
0   01/01/2001             0.5932             0.7084             0.6588   
1   02/01/2001             0.5893             0.7038             0.6576   
2   03/01/2001             0.6000             0.7199             0.6610   
3   04/01/2001             0.5972             0.7021             0.6563   
4   05/01/2001             0.5973             0.6972             0.6532   
5   08/01/2001             0.5987             0.7073             0.6562   
6   09/01/2001             0.5972             0.7095             0.6565   
7   10/01/2001             0.5923             0.7105             0.6548   
8   11/01/2001             0.5888             0.7029             0.6512   
9   12/01/2001             0.5861             0.7013             0.6494   
10  15/01/2001             0.5870             0.7064             0.6492   
11  16/01/2001             0.5892             0.7047             0.6497   
12  17/01/2001             0.5912             0.7070             0.6507   
13  18/01/2001             0.5920             0.7015             0.6544   
14  19/01/2001             0.5953             0.7083             0.6535 

因此,如果我将 startDate 设置为“02/01/2001”,将 endDate 设置为“05/01/2001”

代码将返回:

          date  BBG.BBG.AUDEUR.FX  BBG.BBG.CADEUR.FX  BBG.BBG.CHFEUR.FX  \
0   02/01/2001             0.5893             0.7038             0.6576   
1   03/01/2001             0.6000             0.7199             0.6610   
2   04/01/2001             0.5972             0.7021             0.6563   
3   05/01/2001             0.5973             0.6972             0.6532 

因此,代码不会返回从 CSV 文件导入的所有数据,而是返回开始日期和结束日期之间的数据。

最佳答案

使用pd.to_datetimedtype转换为datetime:

In [98]:
df['date'] = pd.to_datetime(df['date'])
df.info()

<class 'pandas.core.frame.DataFrame'>
Int64Index: 15 entries, 0 to 14
Data columns (total 4 columns):
date                 15 non-null datetime64[ns]
BBG.BBG.AUDEUR.FX    15 non-null float64
BBG.BBG.CADEUR.FX    15 non-null float64
BBG.BBG.CHFEUR.FX    15 non-null float64
dtypes: datetime64[ns](1), float64(3)
memory usage: 600.0 bytes

然后,您可以将日期作为过滤条件传递以创建 bool 掩码:

In [97]:
df[(df['date'] >= '02/01/2001') & (df['date'] <= '05/01/2001')]

Out[97]:
        date  BBG.BBG.AUDEUR.FX  BBG.BBG.CADEUR.FX  BBG.BBG.CHFEUR.FX
1 2001-02-01             0.5893             0.7038             0.6576
2 2001-03-01             0.6000             0.7199             0.6610
3 2001-04-01             0.5972             0.7021             0.6563
4 2001-05-01             0.5973             0.6972             0.6532

关于python - 按数据框中的日期过滤数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36572988/

相关文章:

Python-xlsxwriter 在使用csv数据时只写成文本

python - 在 Python 3.6 中使用 setuptools 打包后的 ModuleNotFoundError

python - 如何使用matplotlib根据条形高度绘制具有特定颜色的3D条形图

python - 将具有 n 级层次索引的 Pandas DataFrame 转换为 n-D Numpy 数组

javascript - python:如何从下载按钮隐藏链接的网页下载数据?

python - 在class1内调用class2时出现AttributeError,class1没有__init__属性

mongodb - 导入到MongoDB/GridFS

python - 如何避免 python 代码中的重复?

python - 从记录中用 Pandas 索引几个 csv 文件?

python - 尝试使用 pygame OpenGL 绘制平面 3D 网格时不断出现错误 1282 'invalid operation'