使用Pandas读取CSV文件:复杂分隔符 [英] Read CSV file using Pandas: complex separator

查看:6325
本文介绍了使用Pandas读取CSV文件:复杂分隔符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,我想使用python panda读取。标题和行如下:

I have a csv file which I want to read using python panda. The header and lines looks the following:

 A           ^B^C^D^E  ^F          ^G           ^H^I^J^K^L^M^N

很明显,它看到,分隔符是^一些奇怪的空间。

Clearly it seen that, separator is ^, sometimes there are some odd spaces. How can I read this file perfectly?

我使用以下命令读取csv文件:

I am using the following command to read the csv file:

df = pd.read_csv('input.csv', sep='^')


推荐答案

使用regex \s * \ ^ 这意味着0或更多的空格和^在这里指定python引擎以避免关于regex支持的警告:

Use regex \s*\^ which means 0 or more whitespace and ^, you have to specify the python engine here to avoid a warning about regex support:

In [152]:

t="""A           ^B^C^D^E  ^F          ^G           ^H^I^J^K^L^M^N"""
df= pd.read_csv(io.StringIO(t), sep='\s*\^', engine='python')
df.columns
Out[152]:
Index(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'], dtype='object')

这篇关于使用Pandas读取CSV文件:复杂分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆