Python如何导入分号和逗号分隔的CSV文件?使用pandas吗?

13

我需要在Windows上使用Python导入一个分号';'分隔的CSV文件,其中包含非英语符号和逗号','的字符串。

我已经阅读过以下帖子:

使用Python将CSV文件导入sqlite3数据库表

Python导入csv到list

当我运行以下命令时:

with open('d:/trade/test.csv', 'r') as f1:
    reader1 = csv.reader(f1)
    your_list1 = list(reader1)

我遇到了一个问题:逗号被改成了破折号符号。

当我尝试以下操作时:

df = pandas.read_csv(csvfile)

我遇到了错误:

pandas.io.common.CParserError: 解析数据时出错。C错误:第13行应该有1个字段,但实际上有2个。

请帮忙解决。我希望使用pandas,因为这样可以通过不列出CSV文件中所有字段名的方式缩短代码。

我知道可以通过临时替换逗号来解决问题,但我更愿意使用一些pandas参数来解决它。


能否提供一小段导致问题的 CSV 数据片段? - totoro
尝试使用以下代码:reader1 = csv.reader(f1, delimiter=';') - Burhan Khalid
5个回答

17

Pandas解决方案 - 使用带有正则表达式分隔符[;,]read_csv。需要添加engine='python',因为会出现警告:

ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'.

import pandas as pd
import io

temp=u"""a;b;c
1;1,8
1;2,1
1;3,6
1;4,3
1;5,7
"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep="[;,]", engine='python')
print (df)

   a  b  c
0  1  1  8
1  1  2  1
2  1  3  6
3  1  4  3
4  1  5  7

2

Pandas文档中对参数的说明如下:

pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html


(备注:此处为直接返回原文,请提供需要翻译的内容)
sep : str, default ‘,’

    Delimiter to use. If sep is None, will try to automatically determine this.

Pandas没有解析我的以;分隔的文件,因为默认值不是自动标记的None,而是,。 添加sep参数设置为;可以解决pandas的问题。


1

除非你的CSV文件已经损坏,否则你可以尝试让csv猜测你的格式。

import csv

with open('d:/trade/test.csv', 'r') as f1:
    dialect = csv.Sniffer().sniff(f1.read(1024))
    f1.seek(0)
    r = csv.reader(f1, dialect=dialect)
    for row in r:
        print(row)

0

为了避免您的代码出现以下警告:

ParserWarning: Falling back to the 'python' engine because the 'c' engine does not support regex separators (separators > 1 char and different from '\s+' are interpreted as regex); you can avoid this warning by specifying engine='python'

在您的read_csv函数中使用属性名称。查看示例,了解出现和不出现此警告的两种情况。

引发警告的代码:

selEncoding = "ISO-8859–1"

dfCovid19DS = pd.read_csv(dsSrcPath, selEncoding)

没有警告的代码:

selEncoding = "ISO-8859–1"

dfCovid19DS = pd.read_csv(dsSrcPath, encoding = selEncoding)

应该给予功劳:这基本上是与 @Santosh-Pathak 两年前给出的答案相同(参考链接)。 - Jeremy Caney

0

尝试指定编码,您需要找出要读取的文件的编码。

我在这个例子中使用了ASCII,但可能会有所不同。

df = pd.read_csv(fname, encoding='ascii')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接