Search code examples
pandasload

How to load text file using pandas?


For example I have this text file named "abc.txt" as below:

#Name : abc
#Date : 1/1/2000
#Country : USA
9000  32  5143  16
2172  26  9162  22
1616  25  7181  40
4626  51  9299  77

I would only want to extract the numbers into dataframe excluding the Name, Date and Country rows


Solution

  • Even though abc.txt is not a CSV file, you can still use the pandas.read_csv() function, since the file is CSV-like enough. Since you want to skip the first three rows, pass any iterable containing the corresponding row index (in this case, that would be any iterable containing 0, 1, and 2). However, passing range(3) would probably be easiest. Since there are no headers, you'll also want to pass header=None.

    >>> pandas.read_csv(
        "abc.txt", delimiter=r"\s+", skiprows=range(3), header=None
    )
          0   1     2   3
    0  9000  32  5143  16
    1  2172  26  9162  22
    2  1616  25  7181  40
    3  4626  51  9299  77