Skip to content
Advertisement

Delete empty dataframes from a list with dataframes

This is a list of dataframes.

import pandas as pd
data=[pd.DataFrame([1,2,3],columns=['a']),pd.DataFrame([]),pd.DataFrame([]),
pd.DataFrame([3,4,5,6,7],columns=['a'])]

I am trying to delete the empty dataframes from the above list that contains dataframes.

Here is what I have tried:

for i in data:
    del i.empty()
data   

which gives:

File "<ipython-input-33-d07b32efe793>", line 2
    del i.empty()
        ^ SyntaxError: cannot delete function call

Important:It needs to store them in the data variable as well

Advertisement

Answer

We ca use filter

data = list(filter(lambda df: not df.empty, data))

or list comprehension

data = [df for df in data if not df.empty]

print(data)

[   a
0  1
1  2
2  3,    a
0  3
1  4
2  5
3  6
4  7]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement