将文本导入到具有多个分隔符的pandas [英] import text to pandas with multiple delimiters

查看:311
本文介绍了将文本导入到具有多个分隔符的pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些看起来像这样的数据:

I have some data that looks like this:

c stuff
c more header
c begin data         
 1 1:.5
 1 2:6.5
 1 3:5.3

我想将其导入3列数据框,其中包含列,例如

I want to import it into a 3 column data frame, with columns e.g.

a , b, c
1,  1, 0.5
etc

我一直试图读取数据将2列拆分为':',然后将第一列拆分为''。但是我发现它令人厌烦。
有没有更好的方法直接在进口时对其进行整理?

I have been trying to read in the data as 2 columns split on ':', and then to split the first column on ' '. However I'm finding it irksome. Is there a better way to sort it out on import directly?

目前:

data1 = pd.read_csv(file_loc, skiprows = 3, delimiter = ':', names = ['AB', 'C'])
data2 = pd.DataFrame(data1.AB.str.split(' ',1).tolist(), names = ['A','B'])

然而,由于我的数据有一个领先的空间,这更加复杂...

However this is further complicated by the fact my data has a leading space...

我觉得这应该是一个简单的任务,但是目前我正在考虑逐行阅读并使用一些查找替换来在导入之前清理数据。

I feel like this should be a simple task, but currently I'm thinking of reading it line by line and using some find replace to sanitise the data before importing.

推荐答案

单向可能是使用python引擎允许的正则表达式分隔符。例如:

One way might be to use the regex separators permitted by the python engine. For example:

>>> !cat castle.dat
c stuff
c more header
c begin data         
 1 1:.5
 1 2:6.5
 1 3:5.3
>>> df = pd.read_csv('castle.dat', skiprows=3, names=['a', 'b', 'c'], 
                     sep=' |:', engine='python')
>>> df
   a  b    c
0  1  1  0.5
1  1  2  6.5
2  1  3  5.3

这篇关于将文本导入到具有多个分隔符的pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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