pandas read_csv.换行前如何忽略定界符 [英] pandas read_csv. How to ignore delimiter before line break

查看:39
本文介绍了 pandas read_csv.换行前如何忽略定界符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取带有数值的文件.

I'm reading a file with numerical values.

data = pd.read_csv('data.dat',sep ='',header = None)

在文本文件中,每行以空格结尾,因此,pandas等待一个不存在的值,并在每行的末尾添加"nan".例如:

In the text file, each row end with a space, So pandas wait for a value that is not there and add a "nan" at the end of each row. For example:

2.343 4.234

2.343 4.234

读取为:[2.343,4.234,nan]

is read as: [2.343, 4.234, nan]

我可以使用,usecols = [0 1] 避免出现这种情况,但我希望使用更通用的解决方案

I can avoid it using , usecols = [0 1] but I would prefer a more general solution

推荐答案

您可以在 sep 参数中使用正则表达式.

You can use regular expressions in your sep argument.

您可以要求它使用任意数量的空格作为分隔符,直到找到下一个值,而不是将分隔符指定为<​​em>一个空间.您可以使用正则表达式 \ s + :

Instead of specifying the separator to be one space, you can ask it to use as a separator any number of spaces until it finds the next value. You can do this by using the regular expression \s+:

data = pd.read_csv('data.dat', sep='\s+', header=None)

这篇关于 pandas read_csv.换行前如何忽略定界符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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