Home > Net >  Iterating over list of dataframes
Iterating over list of dataframes

Time:12-07

I have a list of dfs as such:

ListOfDFs = [DP, SMP, SMD, MP, MD, MSM, SAP, SAD,SAMA, SAM, AP,AD, ASM, AM,ASA]

now I want to iterate over each dataframe to remove NaNs.

I've tried the following:

for i in ListOfDFs[i]:
    i = i.fillna("")

#SMP = SMP.fillna("")
#SMP

However with no success..

CodePudding user response:

assuming you tried

for i in ListOfDFs:

instead of

for i in ListOfDFs[i]:

The reason it doesnt work is with this line

    i = i.fillna("")

i was refering to each dataframe but then it refers to a new dataframe and forgets avout the previous. you use list comprehend to solve it

ListOfDFs = [df.fillna("") for df in ListOfDFs]

this way a new list with nans filled dataframes assigned back to ListOfDFs.

so the issue is not pandas specific

CodePudding user response:

since you mention

remove NaNs

have you tried df.dropna() ?

see this: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.dropna.html

you can apply it, like:

ListOfDFs = [DP, SMP, SMD, MP, MD, MSM, SAP, SAD,SAMA, SAM, AP,AD, ASM, AM,ASA]
    
for i in ListOfDFs[i]:   
    i.dropna() #use arguments if needed
  • Related