Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a text file in pandas with separator as linefeed (\n) and line terminator as two linefeeds (\n\n)

I have a text file of the form :

data.txt

2
8
4

3
1
9

6
5
7

How to read it into a pandas dataframe

  0 1 2
0 2 8 4
1 3 1 9
2 6 5 7
like image 741
Saquib Avatar asked Dec 16 '17 12:12

Saquib


People also ask

How do I read a .TXT file in pandas?

One can read a text file (txt) by using the pandas read_fwf() function, fwf stands for fixed-width lines, you can use this to read fixed length or variable length text files. Alternatively, you can also read txt file with pandas read_csv() function.

How do pandas define separator?

The sep ParameterOne of the optional parameters in read_csv() is sep, a shortened name for separator. This operator is the delimiter we talked about before. This sep parameter tells the interpreter, which delimiter is used in our dataset or in Layman's term, how the data items are separated in our CSV file.

How do I iterate through every row in a DataFrame?

Iterating over the rows of a DataFrame You can do so using either iterrows() or itertuples() built-in methods.


1 Answers

Try this:

with open(filename, 'r') as f:
    data = f.read().replace('\n',',').replace(',,','\n')

In [7]: pd.read_csv(pd.compat.StringIO(data), header=None)
Out[7]:
   0  1  2
0  2  8  4
1  3  1  9
2  6  5  7
like image 162
MaxU - stop WAR against UA Avatar answered Nov 15 '22 06:11

MaxU - stop WAR against UA