标题说明了一切。 伪代码的以下位返回以下错误:
df = pd.read_sql(query, conn, parse_dates=["datetime"],
index_col="datetime")
df['datetime']
我明白了:
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Users\admin\.virtualenvs\EnkiForex-ey09TNOL\lib\site-packages\pandas\core\indexes\base.py", line 2656, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
File "pandas\_libs\hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas\_libs\hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'datetime'
我为索引datetime
的行列误解了吗?我可以正常访问其他所有列。
答案 0 :(得分:2)
索引不是列。将索引视为DataFrame的labels for the rows。 index_col='datetime'
使datetime列(在csv中)成为df
的索引。要访问索引,请使用df.index
。
答案 1 :(得分:0)
import pandas as pd
d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(d)
time = pd.date_range(end='4/5/2018',periods=2)
df.index = time
df.index
结尾是DatetimeIndex(['2018-04-04', '2018-04-05'], dtype='datetime64[ns]', freq='D')
只需使用df.index即可获取index_col的信息