我的csv看起来是这样的:
我正在读取列表中的多个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、和enddate的范围内找到记录。
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)发布于 2022-02-27 18:41:58
您的日期是索引,因此在尝试使用不存在的“日期”列进行选择时会出现一个关键错误。下面是一个玩具示例,说明如何使用索引进行选择。
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 3https://stackoverflow.com/questions/71287447
复制相似问题