0

尝试创建一个字典,键是 csv 文件的第一行,值是 {第一列:对应列到行}的字典:

import pandas as pd

df = pd.read_csv('~/StockMachine/data_stocks.csv', index_col=['DATE'], sep=',\s+')

data = df.to_dict()

print(data)

但是,我收到此错误“ValueError:索引日期无效”。

追溯:

  File "/Users/cs/StockMachine/stockmachine.py", line 4, in <module>
    df = pd.read_csv('~/StockMachine/data_stocks.csv', index_col=['DATE'], sep=',\s+')
  File "/Users/cs/anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 678, in parser_f
    return _read(filepath_or_buffer, kwds)
  File "/Users/cs/anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 446, in _read
    data = parser.read(nrows)
  File "/Users/cs/anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 1036, in read
    ret = self._engine.read(nrows)
  File "/Users/cs/anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 2273, in read
    index, columns = self._make_index(data, alldata, columns, indexnamerow)
  File "/Users/cs/anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 1425, in _make_index
    index = self._get_simple_index(alldata, columns)
  File "/Users/cs/anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 1457, in _get_simple_index
    i = ix(idx)
  File "/Users/cs/anaconda3/lib/python3.6/site-packages/pandas/io/parsers.py", line 1452, in ix
    raise ValueError('Index %s invalid' % col)

data_stocks.csv: CSV 文件

4

2 回答 2

0

类似的事情发生在我身上,在我的情况下,一些读数['DATE']是内部有空格的字符串。也许如果你会做类似的事情:

import pandas as pd

df = pd.read_csv('~/StockMachine/data_stocks.csv', sep=',\s+')

df['DATE'] = df['DATE'].apply(lambda x: str(x.strip())).astype(str)

df.set_index('DATE', inplace=True)

print(df.head())
于 2020-01-22T19:20:30.150 回答
0

我有同样的问题然后意识到 Col_Index 的选定列不是我的脚本中指定的选定 Header=1 行的一部分

于 2022-02-02T11:39:50.017 回答