【问题标题】:Import csv with inconsistent count of columns per row with original header use pandas导入csv,每行列数不一致,原始标题使用熊猫
【发布时间】:2021-04-30 19:36:25
【问题描述】:

请问如何读取该类型的 csv 并保留原始列名?可能会在标题的末尾添加一些通用列名,具体取决于 csv 正文中的最大列数...

a,b,c
1,2,3
1,2,3,
1,2,3,4

简单的 read_csv 不起作用:

tempfile = pd.read_csv(path 
                 ,index_col=None
                 ,sep=','
                 ,header=0
                 ,error_bad_lines=False
                 ,encoding = 'unicode_escape'
                 ,warn_bad_lines=True
                 )
b'Skipping line 3: expected 3 fields, saw 4\nSkipping line 4: expected 3 fields, saw 4\n'

我需要那种结果:

a,b,c,x1
1,2,3,NA
1,2,3,NA
1,2,3,4

【问题讨论】:

  • 您可能需要使用 csv 模块来修复您的文件。
  • @wwnde 我无法使用 cols 名称创建向量,因为我有 cca​​ 1000 csv 文件存在这个问题。

标签: python python-3.x pandas dataframe csv


【解决方案1】:

一种方法是首先读取标题行,然后将这些列名与您的额外通用名称作为参数传递给 pandas。例如:

import pandas as pd
import csv

filename = "input.csv"

with open(filename, newline="") as f_input:
    header = next(csv.reader(f_input))

header += [f'x{n}' for n in range(1, 10)]

tempfile = pd.read_csv(filename,
                 index_col=None,
                 sep=',',
                 skiprows=1,
                 names=header,
                 error_bad_lines=False,
                 encoding='unicode_escape',
                 warn_bad_lines=True,
                 )

skiprows=1 告诉 pandas 跳过标题,names 保存要使用的列标题的完整列表。

然后标题将包含:

['a', 'b', 'c', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6', 'x7', 'x8', 'x9']

【讨论】:

  • 谢谢,您的解决方案正是我所需要的。
猜你喜欢
  • 2023-03-13
  • 2019-08-12
  • 2020-02-19
  • 2020-02-10
  • 1970-01-01
  • 1970-01-01
  • 2022-01-06
  • 1970-01-01
  • 2021-10-09
相关资源
最近更新 更多