使用Datetime索引筛选pandas csv数据帧



我的csv如下所示:
|Date|Open|High|Low|Close|Adj Close|Vol||----|----|----|----|----|----|----||2008年1月29日| 9.5 | 9.99 | 8.57 | 8.75 | 0.702589 | 1489000 |

我正在读取列表中的多个csv文件;日期";作为索引并解析日期:

all_max = []
for f in max_files:
data_instance = pd.read_csv(os.path.join(max_path, f), index_col=0, parse_dates=['Date'])
all_max.append(data_instance)

我想查找开始日期结束日期

startdate = pd.to_datetime("2010-7-7").date()
enddate = pd.to_datetime("2010-7-15").date()
locs = all_max[0]['Date'].iloc[startdate:enddate]
print(locs)

但是我得到一个错误

KeyError: 'Date'
The above exception was the direct cause of the following exception:
KeyError                                  Traceback (most recent call last)
<ipython-input-119-580774846bf5> in <module>
1 startdate = pd.to_datetime("2010-7-7").date()
2 enddate = pd.to_datetime("2010-7-15").date()
----> 3 locs = all_max[0]['Date'].iloc[startdate:enddate]
4 print(locs)

您的日期是索引,因此在尝试使用"日期";不存在的列。下面是一个如何使用索引进行选择的玩具示例。

import pandas as pd
df = pd.DataFrame({'Date': ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04', '2022-01-05'],
'this': [5,2,2,5,5], 
'that': [3,3,3,3,3]},
)
df.to_csv('dates.csv', index=False)
dates  = pd.read_csv('dates.csv', index_col=0, parse_dates=['Date'])
dates = dates.loc[(dates.index > '2022-01-01') & (dates.index <= '2022-01-03')]

输出:

this    that
Date        
2022-01-02  2       3
2022-01-03  2       3

iloc用于整数索引,即按行位置进行索引。

请尝试使用loc。还要注意,panda接受日期作为字符串,并为您进行必要的转换。

startdate = "2010-7-7"
enddate = "2010-7-15"
selection = all_max[0].loc[startdate:enddate]
dates = selection.index

最新更新