How to skip blank lines with read_fwf in pandas?

I use pandas.read_fwf()pandas 0.19.2 in Python to read a file fwf.txtthat has the following contents:

# Column1 Column2
      123     abc

      456     def

#
#

My code is as follows:

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 data circuit is as follows:

    Column1 Column2
0   123.0   abc
1   NaN     NaN
2   456.0   def
3   NaN     NaN

The argument seems to be skip_blank_lines=Trueignored, as the dataframe contains NaN.

What should be a valid combination of arguments pandas.read_fwf()that would allow skipping blank lines?

+4
source share
1 answer
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. iterable) that gives lines from a file with empty lines removed.

pd.read_fwf TextIOBase. TextIOBase, readline :

class FileLike(io.TextIOBase):
    def __init__(self, iterable):
        self.iterable = iterable
    def readline(self):
        return next(self.iterable)

/ pd.read_fwf.

+1

Source: https://habr.com/ru/post/1671370/


All Articles