如何通过数字和空格使read_csv更灵活

时间:2019-05-23 08:12:04

标签: python pandas csv

我想用熊猫来读txt.file,问题是数字的分隔符/分隔符,然后是最少两个空格。

我已经尝试过类似于此代码(How to make separator in pandas read_csv more flexible wrt whitespace?):

pd.read_csv("whitespace.txt", header=None, delimiter=r"\s+")

这仅在空白或更多的情况下有效。因此,我将其调整为以下代码。

delimiter=r"\d\s\s+"

但是,当看到两个或多个空白时,这会将我的数据框分隔开,但是我严格要求先输入数字,然后再输入至少两个空白,有人知道如何修复它吗?

我的数据如下:

I am an example of a dataframe
I have Problems to get read
100,00
So How can I read it
20,00

因此第一行应为: I am an example of a dataframe I have Problems to get read 100,00 第二行: So HOw can I read it 20,00

1 个答案:

答案 0 :(得分:1)

Id像这样尝试。

Id在尝试将文本文件解析为数据框之前先对其进行如下操作:

import pandas as pd
import re

f = open("whitespace.txt", "r")
g = f.read().replace("\n", " ")

prepared_text = re.sub(r'(\d+,\d+)', r'\1@', g)

df = pd.DataFrame({'My columns':prepared_text.split('@')})
print(df)

这给出了以下内容:

                                          My columns
0  I am an example of a dataframe I have Problems...
1                         So How can I read it 20,00
2 

我想只要输入文件不是太大就足够了,但是使用re模块和替换可以给您所需的控制权。

(\ d +,\ d +)括号标记了我们要匹配的组。我们基本上是在您的文本文件中匹配您的任何号码。 然后,我们使用\ 1,它被称为对匹配组的反向引用,在指定替换项时将被引用。因此,\ d +,\ d +替换为\ d +,\ d + @。

然后我们将插入的字符用作分隔符。

这里有一些很好的例子:

https://lzone.de/examples/Python%20re.sub