python - KeyError:“日期”我使用 set_index 错了吗?
问题描述
当我运行代码时,
import pandas as pd
import io
df = pd.read_table("./stock.txt", names=["ID", "Date","Open","High","Low","Close"])
df
del df['ID']
df=df.set_index(["Date"])
df
发生此错误
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~/anaconda3/envs/py/lib/python3.6/site-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance)
3062 try:
-> 3063 return self._engine.get_loc(key)
3064 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Date'
我阅读了set_index的pandas文档,但是为什么会发生这样的错误?在第一个 df 中,DataFrame 显示为
"Date" "Open" "High" "Low" "Close"
2010-04-01 3,615 3,615 3,580 3,585
2010-04-02 3,570 3,620 3,570 3,590
・
・
・
我理想的第二个 DataFrame 是
"Open" "High" "Low" "Close"
"Date"
2010-04-01 3,615 3,615 3,580 3,585
2010-04-02 3,570 3,620 3,570 3,590
・
・
・
要制作这样一个理想的 DataFrame ,我应该如何修复我的代码?出了什么问题?我的文本文件就像
1,1001 2010-04-01 3,615 3,615 3,580 3,585
2,1002 2010-04-02 3,570 3,620 3,570 3,590
・
・
・
解决方案
我认为最好在这里使用:
df = pd.read_table("./stock.txt",
sep='\s+', #if separator is whitespace
names=["ID", "Date","Open","High","Low","Close"],
parse_dates=['Date'],
index_col=['Date'],
thousands=',')
选择:
df = pd.read_csv("./stock.txt",
sep='\s+', #if separator is whitespace
names=["ID", "Date","Open","High","Low","Close"],
parse_dates=['Date'],
index_col=['Date'],
thousands=',')
不同之处:
默认分隔符read_table
是tab
( sep=\t
) 和 forread_csv
是逗号 ( sep=','
)。
编辑:
使用您的样本数据进行测试:
import pandas as pd
temp=u"""1,1001 2010-04-01 3,615 3,615 3,580 3,585
2,1002 2010-04-02 3,570 3,620 3,570 3,590"""
#after testing replace 'pd.compat.StringIO(temp)' to 'filename.csv'
df = pd.read_csv(pd.compat.StringIO(temp),
sep="\s+", #or sep='\t'
usecols=["Date","Open","High","Low","Close"],
names=["ID", "Date","Open","High","Low","Close"],
parse_dates=['Date'],
index_col=['Date'],
thousands=',')
print (df)
Open High Low Close
Date
2010-04-01 3615 3615 3580 3585
2010-04-02 3570 3620 3570 3590
推荐阅读
- python-3.x - Datetime 函数使用 datetime.strptime() 返回错误
- thymeleaf - 链接中的变量
- ionic-framework - Ionic5 HttpErrorResponse
- c# - 在我的 c# 项目中有一个 powershell 文件,我可以在我的代码中运行
- grafana - 过滤整数范围
- python-3.x - Discord.py 不加载命令
- python - keras model.fit ValueError:indices.shape=[1,11,1] 的外部 2 维必须与 updates.shape=[2] 的外部 2 维匹配
- javascript - 使用 Google Drive API v3 JavaScript 上传到 Google Drive 时名为“Untitled”的文件
- python - Tkinter:有没有办法不进入凸起框架后面的小部件?
- php - 使用 PDFtk 根据 PHP 中的参数选择特定的 PDF 文件