Search code examples
pythonpandasdataframeis-empty

how to create python empty dataframe where df.empty results in True


How can I create an empty dataframe in python such that the test df.empty results True?

I tried this:

df = pd.DataFrame(np.empty((1, 1)))

and df.empty results in False.


Solution

  • The simplest is pd.DataFrame():

    df = pd.DataFrame()   
    
    df.empty
    # True
    

    If you want create a data frame of specify number of columns:

    df = pd.DataFrame(columns=['A', 'B'])
    
    df.empty
    # True
    

    Besides, an array of shape (1, 1) is not empty (it has one row), which is the reason you get empty = False, in order to create an empty array, it needs to be of shape (0, n):

    df = pd.DataFrame(pd.np.empty((0, 3)))
    
    df.empty
    # True