2

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.

Galen
  • 31
  • 1
  • 5
  • 2
    Try `pd.read_csv(r'file.txt', sep='\\s+', header=None)`. Your data is read in as a single column because you have not specified the correct separator. – Trenton McKinney Oct 16 '19 at 04:45

2 Answers2

2
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

ArunJose
  • 1,999
  • 1
  • 10
  • 33
  • When copy pasted from the snippet the delimiter was interpreted as tabs in my machine not sure if it is different for others – ArunJose Oct 16 '19 at 05:00
-2

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')

lobetdenherrn
  • 303
  • 1
  • 8