【发布时间】:2018-05-16 10:05:06
【问题描述】:
我有一个包含 7 列的 csv 文件 ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
问题是我尝试设置日期时间索引,但它不起作用可能是因为日期和时间是两个单独的列。
代码如下:
import pandas as pd
column_names = ['Date', 'Time', 'Open', 'High', 'Low','Close', 'Volume']
df = pd.read_csv(r"E:\Tutorial\EURUSD60.csv", header=None, names=column_names)
df['DateTime'] = pd.to_datetime(df['Date', 'Time'])
print(df.head())
这是错误:
C:\Users\sydgo\Anaconda3\python.exe E:/Tutorial/language.py Traceback (最近一次通话最后):文件 "C:\Users\sydgo\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", 第 2442 行,在 get_loc 中 返回 self._engine.get_loc(key) 文件“pandas_libs\index.pyx”,第 132 行,在 pandas._libs.index.IndexEngine.get_loc 文件中 “pandas_libs\index.pyx”,第 154 行,在 pandas._libs.index.IndexEngine.get_loc 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1210 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1218 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: ('Date', '时间')
在处理上述异常的过程中,又发生了一个异常:
Traceback(最近一次调用最后一次):文件“E:/Tutorial/language.py”, 第 7 行,在 df['DateTime'] = pd.to_datetime(df['Date', 'Time']) 文件 "C:\Users\sydgo\Anaconda3\lib\site-packages\pandas\core\frame.py", 第 1964 行,在 getitem 中 返回 self._getitem_column(key) 文件 "C:\Users\sydgo\Anaconda3\lib\site-packages\pandas\core\frame.py", 第 1971 行,在 _getitem_column 返回 self._get_item_cache(key) 文件 "C:\Users\sydgo\Anaconda3\lib\site-packages\pandas\core\generic.py", 第 1645 行,在 _get_item_cache 中 值 = self._data.get(item) 文件“C:\Users\sydgo\Anaconda3\lib\site-packages\pandas\core\internals.py”, 第 3590 行,在获取 loc = self.items.get_loc(item) 文件 "C:\Users\sydgo\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", 第 2444 行,在 get_loc 中 return self._engine.get_loc(self._maybe_cast_indexer(key)) 文件“pandas_libs\index.pyx”,第 132 行,在 pandas._libs.index.IndexEngine.get_loc 文件 “pandas_libs\index.pyx”,第 154 行,在 pandas._libs.index.IndexEngine.get_loc 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1210 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item 文件 “pandas_libs\hashtable_class_helper.pxi”,第 1218 行,在 pandas._libs.hashtable.PyObjectHashTable.get_item KeyError: ('Date', '时间')
【问题讨论】:
-
这个stackoverflow.com/a/46483409/4800652 可能会有所帮助