Telling python to ignore undefined data frames while iterating over a list of data frames?

213
December 01, 2017, at 08:58 AM

Consider this dataframe and iteration:

pdata= {'col1': [1, 2], 'col2': [3, 4]}
pdata= pd.DataFrame(data=pdata)

for i in [pdata, vdata, odata]:
    i.index  = i.iloc[:, 0]

if any of pdata, vdata, or odata is not defined, Python throws the error:

NameError: name 'vdata' is not defined

Occasionally, I want to run the command while vdata and odata are not yet defined. What is the way to tell python to do the operation on the defined objects in the list and simply ignore the undefined ones?

Answer 1

Just skip over the errors with a try-except clause:

try:
    for i in [pdata, vdata, odata]:
        i.index  = pd.DatetimeIndex(i.date)
except:
    # You can do whatever you want here; pass does nothing
    pass
Answer 2
pdata= {'col1': [1, 2], 'col2': [3, 4]}
pdata= pd.DataFrame(data=pdata)
if pdata in locals():
    for i in [pdata]:
        i.index = i.iloc[:, 0]
if vdata in locals():    
    for i in [vdata]:
        i.index  = i.iloc[:, 0]
if odata in locals():
    for i in [odata]:
        i.index = i.iloca[:, 0] 

I can't test this at the moment, but what if we check it in locals() in a if condition, would that satisfy? Try it out.

hard to reproduce since I don't have all the code.

Rent Charter Buses Company
READ ALSO
Python beep not working

Python beep not working

The python winsound beep is not working with selected audio outputIt works when I have headphones plugged into rear output, but i need it to work with digital output

365
Django unable to migrate PostgreSQL: constraint X of relation Y does not exist

Django unable to migrate PostgreSQL: constraint X of relation Y does not exist

I'm trying to run a Django 111 migration on a PostgreSQL 9

312
I must plot each function for each item in my list, not working

I must plot each function for each item in my list, not working

This is supposed to create four graphs for each graphing method in 'plotters', it only creates 1 graph, specifically plotters[1] and/or plotters[3] (They look the same)Its a lab that i need to do for school

305