gpt4 book ai didi

python - 使用 pandas.read_csv 设置标题

转载 作者:太空狗 更新时间:2023-10-29 21:58:53 28 4
gpt4 key购买 nike

我有一个 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)

这给出了以下错误-

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

然后我尝试通过

设置列
df.columns = header_row

但是这个错误可能是因为重复的列值。

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')

我使用的是 pandas 0.7.3 版本。来自文档 -

名称:类似数组 列名列表

我确定我在这里遗漏了一些简单的东西。感谢您的帮助。

最佳答案

Pandas 0.7.3 不支持索引重复。您至少需要 0.8.0,在 0.8.0 和 0.8.1 之间,索引中重复的几个问题已得到修复,因此 0.8.1(=最新的稳定版本)可能是最好的。然而,即使是 0.8.1 也不能解决你的问题,因为这个版本有一个 issue具有重复的列名(您不能显示具有重复列名的数据框)。

关于python - 使用 pandas.read_csv 设置标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12066550/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com