0

I'm using python 3.x.I would like to delete all pandas dataframe created by my python code. I know there is an option

del df

to delete dataFrame df. But I'm looking something similar to R command

rm(list=ls())

to remove all available dataframe created by my code. Can you please suggest?

Soumendra Mishra
  • 3,483
  • 1
  • 12
  • 38
newinPython
  • 313
  • 1
  • 6
  • 19
  • Does [This](https://stackoverflow.com/questions/32247643/how-to-delete-multiple-pandas-python-dataframes-from-memory-to-save-ram) answer? – AbbasEbadian Sep 07 '20 at 09:54
  • Please change the tags. this is an R question and not a python – gtomer Sep 07 '20 at 09:54
  • @gtomer I'm asking for python & I need something similar to R,I guess only python experts can able to answer this, not the R expert – newinPython Sep 07 '20 at 10:47
  • @AbbasEbadian, no it's not helping. I'm looking for some wildcard entry,not to mention the dataframe name. I tried garbage collection one. But after running that also I can able to run head() with my dataframe name – newinPython Sep 07 '20 at 10:52

1 Answers1

2

It's not as straightforward in Python as it is in R. The best and safest option is to manually del each dataframe by name (as well as any other references to the object, e.g. if they are also in a list). However, if this isn't an option, you can iterate through all available variables, check if they are an instance of a pandas Dataframe, and then delete them.

If your goal is to free memory, you should manually run garbage collection after references to the objects have been deleted.

The following works for me:

import gc
import pandas as pd

for i in dir():
    if isinstance(globals()[i], pd.DataFrame):
        del globals()[i]

gc.collect()
amin_nejad
  • 989
  • 10
  • 22