简体   繁体   中英

Delete empty dataframe with loop in Python

I have a serie of different DataFrame in Python. I want to check if each of them is either empty or not and then delete those that are actually empty. I am trying with a loop but none dataframes are actually deleted, also those that are actually empty. Here the example, where df_A , df_B , df_C , and df_D are my dataframes and the last one ( df_D ) is empy.

df_names = [df_A, df_B, df_C, df_D]
for df_ in df_names:
    if df_.empty: del df_

For sure I am missing something quite simple, I hope you can help me with this (probably a bit silly) question.

You can use the python locals() function to do this. I would first save the dataframes in a list as string :

Code

df_names = ['df_A', 'df_B', 'df_C', 'df_D']
for df_ in df_names:
    if locals()[df_].empty:
        del locals()[df_]

You can also check if your dataframe has been deleted using the below code:

alldfs = [var for var in dir() if isinstance(eval(var), pd.core.frame.DataFrame)]
for i in alldfs:
    if i[:1] != '_':
        print (i)

The above snippet will return all the existing dataframes (excluding the ones defined by python internally)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM