【问题标题】:Count number of columns in multiple csv files in directory计算目录中多个 csv 文件中的列数
【发布时间】:2019-01-31 12:37:00
【问题描述】:

我有一个目录,其中包含大量 CSV 文件(超过 1000 个)。我正在使用 python pandas 库来计算每个 CSV 文件中的列数。

但问题是某些CSV文件中使用的分隔符不仅是"," but "|" and ";"

如何解决这个问题:

import pandas as pd
import csv
import os
from collections import OrderedDict

path="C:\\Users\\Username\\Documents\\Sample_Data_August10\\outbound"

files=os.listdir(path)

col_count_dict=OrderedDict() 
for file in files:
    df=pd.read_csv(os.path.join(path,file),error_bad_lines=False,sep=",|;|\|",engine='python')

    col_count_dict[file]=len(df.columns)

我将它存储为字典。

我收到如下错误:

Error could possibly be due to quotes being ignored when a multi-char delimiter is used

我用过sep=None,但没用。

编辑
其中一个csv是这样的Number|CommentText|CreationDate|Detail|EventDate|ProfileLocale_ISO|Event_Number|Message_Number|ProfileInformation_Number|Substitute_UserNo|User_UserNo
第二个是这样的: Number,Description

我无法透露数据。我刚刚给出了列名,因为数据很敏感。

更新

经过一些调整并使用打印状态来找出使用 andrey-portnoy 的代码后,我知道 csv 嗅探器正在识别“|”的分隔符作为“e”,所以使用 if 语句我将其改回“|”。现在它给了我正确的输出。
同样代替 read() ,我使用了 readline() 。在安德烈的答案中的以下代码行中:dialect = csv.Sniffer().sniff(csvfile.read(1024))
但问题仍未解决。经过大量检查后,我能够弄清楚这一点,但每次我可能都猜对不正确,这可能会导致错误。
我们将等待任何帮助。

【问题讨论】:

  • 嘿@Atif。您是否尝试过在不使用 sep= 的情况下运行它? Pandas 在为您制定分隔符方面做得非常好。所以... “df=pd.read_csv(os.path.join(path,file),error_bad_lines=False,engine='python')”
  • @ChrisA ,不,它不起作用。即使具有“|”的分隔符不是 1,它也会将列计数为 1

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


【解决方案1】:

通过将分隔符指定为sep=",|;|\|",您可以使整个字符串成为分隔符。

相反,您想使用 csv 模块中的 Sniffer 来检测每个文件中使用的 CSV 方言,尤其是分隔符。

例如对于单个文件example.csv

import csv
with open('example.csv', newline='') as csvfile:
    dialect = csv.Sniffer().sniff(csvfile.read(1024))
sep = dialect.delimiter

df = pd.read_csv('example.csv', sep=sep)

默认情况下不要启用 Python 引擎,因为它要慢得多。

【讨论】:

  • 我试过这个,但我得到一个错误:raise Error, "Could not determine delimiter" _csv.Error: Could not determine delimiter
  • @Atif 你能在 CSV 文件中包含几行吗?
  • @Atif 如果在文件上运行pd.read_csv(file, sep='|') 并以| 作为分隔符会发生什么?
  • 我尝试打印 sep 以查看它是否正确捕获分隔符并发现对于“|”将 sep 作为 "e" 的分隔文件。这就是它失败的原因。
  • 如果我给 sep="|"它为该文件提供了正确的输出
猜你喜欢
  • 1970-01-01
  • 2017-09-05
  • 2016-12-15
  • 2014-05-30
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 2012-09-29
相关资源
最近更新 更多