parsing empty file with no columns

后端 未结 2 1640
傲寒
傲寒 2021-01-22 00:31

I have a function that reads a text file and then parses it into a data frame.

Usually the input file will be something like this:

A   B   M
1   2   100
         


        
相关标签:
2条回答
  • 2021-01-22 01:13

    Just eat the exception and make an empty df:

    def read_data(file):
        try:
            df = pd.read_csv(file, delim_whitespace=True)
        except pandas.io.common.EmptyDataError:
            df = pd.DataFrame()
    
        return df
    
    0 讨论(0)
  • 2021-01-22 01:16

    There are ways you can validate that a file is empty or formatted incorrectly. However, you can also just catch the exception and return an empty data frame.

    from pandas.io.common import EmptyDataError
    
    def read_data(file):
        try:
            df = pd.read_csv(file, delim_whitespace=True)
        except EmptyDataError:
            df = pd.DataFrame()
    
        return df
    
    0 讨论(0)
提交回复
热议问题