Ale*_*nov 7 python csv separator dataframe pandas
我需要在Windows上用Python导入CSV文件.我的文件由';'分隔 并且包含非英语符号和逗号(',')的字符串.
我看了帖子:
当我跑:
with open('d:/trade/test.csv', 'r') as f1:
reader1 = csv.reader(f1)
your_list1 = list(reader1)
Run Code Online (Sandbox Code Playgroud)
我遇到了一个问题:逗号更改为" - "符号.
当我尝试:
df = pandas.read_csv(csvfile)
Run Code Online (Sandbox Code Playgroud)
我有错误:
pandas.io.common.CParserError:标记数据时出错.C错误:第13行预计有1个字段,见2.
请帮忙.我更喜欢使用pandas,因为代码较短而没有列出CSV文件中的所有字段名称.
我知道可能有暂时替换逗号的工作.不过,我想通过一些参数解决它到熊猫.
jez*_*ael 11
熊猫解决方案 - read_csv与正则表达式分隔符一起使用[;,].你需要添加engine='python',因为警告:
ParserWarning:回退到'python'引擎,因为'c'引擎不支持正则表达式分隔符(分隔符> 1个字符,不同于'\ s +'被解释为正则表达式); 您可以通过指定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
Run Code Online (Sandbox Code Playgroud)