How do I read a fixed width format text file in pandas?

user1234440 picture user1234440 · Mar 15, 2012 · Viewed 16.9k times · Source

I just got my hands on pandas and am figuring out how I can read a file. The file is from the WRDS database and is the SP500 constituents list all the way back to the 1960s. I checked the file and no matter what I do to import it using read_csv, I still can't display the data correctly.

df = read_csv('sp500-sb.txt')

df

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1231 entries, 0 to 1230
Data columns: gvkeyx      from      thru     conm
                                        gvkey      co_conm
...(the column names)
dtypes: object(1)

What does the above chunk of output mean? Anything would be helpful.

Answer

WoodChopper picture WoodChopper · Oct 27, 2015

pandas.read_fwf() was added in pandas 0.7.3 (April 2012) to handle fixed-width files.

  1. API reference

  2. An example from other question