How to fix an error code that removes whitespace separating columns in fwf file python pandas read_fwf

172 views Asked by At

I am reading in an fwf file (using python/pandas' read_fwf) that normally has 2-3 spaces between the columns. However, when a certain error is thrown, the error code produced in the second column takes up extra spaces, and therefore removes the whitespace between the first and second columns, so the computer reads it as one column instead of two. How can I either add in another whitespace when this error is thrown, or set the space-width of the column to be x-number of spaces/characters and then assume that after that x-number of spaces/characters is another column?

ex: the first 3 lines below are how the code should look, and the fourth line is when the error "A" is thrown and the second column takes up so much space that it removes the white space.

   0.11  -0.45   0.40 -104.57   2
   0.11  -0.45   0.40 -104.57   2
   0.15  -0.46   0.37 -104.60   2
 -61.98-108.29 -72.07   -9.51   A
1

There are 1 answers

0
Tzane On

Try defining a colspecs to read_fwf, file.txt copied from your sample:

import pandas as pd

colspecs = [(0, 7), (7, 14), (14, 21), (21, 29), (29, 33)]
df = pd.read_fwf("file.txt", colspecs=colspecs, header=None)
print(df)