I use pandas.read_fwf()
function in Python pandas 0.19.2 to read a file fwf.txt
that has the following content:
# Column1 Column2
123 abc
456 def
#
#
My code is the following:
import pandas as pd
file_path = "fwf.txt"
widths = [len("# Column1"), len(" Column2")]
names = ["Column1", "Column2"]
data = pd.read_fwf(filepath_or_buffer=file_path, widths=widths,
names=names, skip_blank_lines=True, comment="#")
The printed dataframe is like this:
Column1 Column2
0 123.0 abc
1 NaN NaN
2 456.0 def
3 NaN NaN
It looks like the skip_blank_lines=True
argument is ignored, as the dataframe contains NaN's.
What should be the valid combination of pandas.read_fwf()
arguments that would ensure the skipping of blank lines?
import io
import pandas as pd
file_path = "fwf.txt"
widths = [len("# Column1 "), len("Column2")]
names = ["Column1", "Column2"]
class FileLike(io.TextIOBase):
def __init__(self, iterable):
self.iterable = iterable
def readline(self):
return next(self.iterable)
with open(file_path, 'r') as f:
lines = (line for line in f if line.strip())
data = pd.read_fwf(FileLike(lines), widths=widths, names=names,
comment='#')
print(data)
prints
Column1 Column2
0 123 abc
1 456 def
with open(file_path, 'r') as f:
lines = (line for line in f if line.strip())
defines a generator expression (i.e. an iterable) which yields lines from the file with blank lines removed.
The pd.read_fwf
function can accept TextIOBase
objects. You can subclass
TextIOBase
so that its readline
method returns lines from an iterable:
class FileLike(io.TextIOBase):
def __init__(self, iterable):
self.iterable = iterable
def readline(self):
return next(self.iterable)
Putting these two together gives you a way to manipulate/modify lines of a file
before passing them to pd.read_fwf
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With