我有一个csv文件,我使用pandas API读入数据帧.我打算设置自己的标头而不是默认的第一行.(我也摆脱了一些行.)我如何才能最好地实现这一目标?
我尝试了以下但是这没有按预期工作:
header_row=['col1','col2','col3','col4', 'col1', 'col2'] # note the header has duplicate column values
df = pandas.read_csv(csv_file, skiprows=[0,1,2,3,4,5], names=header_row)
Run Code Online (Sandbox Code Playgroud)
这给出了以下错误 -
File "third_party/py/pandas/io/parsers.py", line 187, in read_csv
File "third_party/py/pandas/io/parsers.py", line 160, in _read
File "third_party/py/pandas/io/parsers.py", line 628, in get_chunk
File "third_party/py/pandas/core/frame.py", line 302, in __init__
File "third_party/py/pandas/core/frame.py", line 388, in _init_dict
File "third_party/py/pandas/core/internals.py", line 1008, in form_blocks
File "third_party/py/pandas/core/internals.py", line 1036, in _simple_blockify
File "third_party/py/pandas/core/internals.py", line 1068, in _stack_dict
IndexError: index out of bounds
Run Code Online (Sandbox Code Playgroud)
然后我尝试通过设置列
df.columns = header_row
Run Code Online (Sandbox Code Playgroud)
但这可能是由于重复的列值导致错误.
File "engines.pyx", line 101, in pandas._engines.DictIndexEngine.get_loc
(third_party/py/pandas/src/engines.c:2498)
File "engines.pyx", line 107, in pandas._engines.DictIndexEngine.get_loc
(third_party/py/pandas/src/engines.c:2447)
Exception: ('Index values are not unique', 'occurred at index entity')
Run Code Online (Sandbox Code Playgroud)
我正在使用pandas 0.7.3版本.从文档 -
names:类似列名列表
我相信我在这里缺少一些简单的东西.感谢您的帮助.