0

New to Python but here is the code I'm using:

lst2 = list()
for i in lst1:
   try: 
      df1 = pd.DataFrame(i.QID1)
except AttributeError:
      "null"
df2 = lst2.append(df1)

lst2 is generating the output that I want, but the instances where i.QID1 does not exist are being populated by the data from the previous instance, instead of "null". I'm sure it's because of the 'except AttributeError' piece, just not sure how to fix it. As I say I'm a noob.

Thanks so much for any help!

1 Answer 1

1

Your indentation is off, and you didn't assign the "null" value to anything.

lst2 = list()
for i in lst1:
    try: 
        df1 = pd.DataFrame(i.QID1)
    except AttributeError:
        df1 = "null"
    lst2.append(df1)
  • Everything has to be indented under the for loop if you want it to happen inside the loop.
  • The try and except need to be at the same level of indentation.
  • Appending df1 to lst2 doesn't return anything, so there's no point assigning it to df2.

Another way to build this list could be to write a function that returns the dataframe (or "null") for a given i and use that in a comprehension:

def dataframe_or_null(i):
    try: 
        return pd.DataFrame(i.QID1)
    except AttributeError:
        return "null"

lst2 = [dataframe_or_null(i) for i in lst1]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.