【问题标题】:python pandas shape data off CSV fileCSV文件中的python pandas形状数据
【发布时间】:2017-08-25 01:49:41
【问题描述】:

我在CSV 文件中有一个数据集,该文件从会计应用程序下载到CSV 文件中。数据的结构方式很好,除了它被分成几页。因此,CSV 文件包含不需要的垃圾行:

Company:ABC Ltd Date: 30-Mar-2017
GL Download

                                              Page No 1

GL Code,GL Name,Journal Id,Amount $,Vendor,Vendor Code,Text
1001200,SalesUK,5060400604,1,234.34,GroveT,234565,FC approved

更多数据在这里......

Company:ABC Ltd Date: 30-Mar-2017
GL Download

                                              Page No 2

GL Code,GL Name,Journal Id,Amount $,Vendor,Vendor Code,Text
34560432,SalesUK,5060434567,4,356.19,Legend,135678,checked

每次到达分页符时,标题都会重复。我正在尝试将数据从CSV 文件上传到pandas.DataFrame,但问题在于我需要删除的那些分页符和重复的标题。

pandas 或 python csv 模块中是否有标准解决方案来克服数据行,例如页码和页眉?

【问题讨论】:

  • 如果您知道(或可以计算)攻击性数据的确切行号,您可以告诉pandas.read.csv() 忽略这些行。
  • @DYZ 你的意思是pd.read_csv(filepath)?你能澄清一下如何帮助摆脱垃圾线吗?我认为 read_csv 构造函数中的skip_blank_rows 可能会有所帮助,但它只会跳过空白行。在我的情况下,垃圾行中的一些单元格被填充。除了这个问题,我还在每一页上重复了标题。
  • 是的,我的意思是read_csv,抱歉打错了。查看skiprows 选项。但我想一个更好的解决方案是将error_bad_lines 设置为False,然后从数据框中删除“脏”行。

标签: python csv pandas parsing


【解决方案1】:

Pandas 允许您传递自己的解析器。如果您传递参数engine='python',则期望filepath_or_buffer(第一个参数)将是一个返回列表的迭代器。这与csv 模块的作用相同。因此,您可以提供与此签名匹配的生成器,例如:

代码:

此代码为相关报告格式提供自定义解析器。它只产生数据线。

def my_csv_reader(csvfile_handle):

    looking_for_header = True
    prev_line_blank = False
    for line in (x.strip() for x in csvfile_handle.readlines()):
        blank_line = len(line.strip()) == 0
        if looking_for_header:
            if not blank_line and prev_line_blank:
                looking_for_header = not line.startswith('GL Code,')
        elif not blank_line:
            yield line
        else:
            looking_for_header = True

        prev_line_blank = blank_line

使用解析器的代码:

要使用解析器,我们打开文件,从该文件构造一个 csv_reader 生成器,然后调用pandas.csv_reader():

with open('report.csv', 'rU') as csvfile:
    reader = csv.reader(my_csv_reader(csvfile))
    df = pd.read_csv(
        reader, engine='python', header=None, index_col=False,
        names='GL Code,GL Name,Journal Id,Category,Amount $' \
              ',Vendor,Vendor Code,Text'.split(',')
    )

示例结果:

    GL Code  GL Name  Journal Id  Category  Amount $  Vendor  Vendor Code  \
0   1001200  SalesUK  5060400604         1    234.34  GroveT       234565   
1  34560432  SalesUK  5060434567         4    356.19  Legend       135678   

          Text  
0      checked  
1  FC approved  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 2014-02-07
    • 1970-01-01
    • 2021-09-23
    • 2021-05-14
    • 2021-12-08
    • 2014-01-21
    相关资源
    最近更新 更多