Problems with Pandas reading txt file

Viewed 2339

I am having a rough time getting my code (python 3) to read a txt file. I am using Pandas to get it to work and I have it read the file and gets the right number of rows, but the module reads the file as one column and makes the entire dataframe into one column 0. Here is an example of the code.

import pandas as pd
import numpy as np


data = pd.read_csv(r'file.txt',header=None)

I have used the delimiters/seperaters setup too in the line of code like \t or ' ' but it couldn't read the file then. Here is an example of what the file looks like.

  JK+0923  7.05  19.3 200.4 -56.1   0.140   0.022 2010 GHT-Jermi

As you can see, there is no header. Either way, would like help. Thanks. I want it to read the columns correctly.

2 Answers
import pandas as pd
import numpy as np


data = pd.read_csv(r'asd.txt',header=None,sep='\t')

This should work if thedelimiter in your case is tab

or you can use a regex like \s+ for the value of sep for accepting multiple spaces as delimiter

The pd.read_csv() function expects a header when used in the standard way. However, you can specify the header=None parameter, see this question for more details:

Pandas read in table without headers

As you pointed out in your question, you have already tried to specify the delimiter when reading in the file, so the combination of both should help you read the file in correctly:

data = pd.read_csv(r'file.txt',header=None, sep='\t')

Related