0

I want to merge 2 DataFrames using a function. The function creates DataFrame df1 when called with variable 'x=1', and then another, df2, when called with 'x != 1', based on an if-statement within the function - code snippet below for further clarity.

Upon reaching the "df3 = pd.concat" line, I get the error "UnboundLocalError: local variable 'df1' referenced before assignment".

I would like to understand how to achieve the result of concatenating df1 and df2 into df3.

def Concat(url, x):
    if x == 1:
        df1 = pd.read_json(url)
    else:
        df2 = pd.read_json(url)
        df3 = pd.concat([df1, df2], ignore_index=True)


def main():
    Concat('*url*', 1)
    Concat('*url*', 2)
2
  • 2
    In the else block, you never define df1, so you get the UnboundLocalError. Commented Aug 23, 2021 at 1:35
  • 2
    both df1 and df2 are generated that's where you're wrong. You have code for generating both but it will never run together. Commented Aug 23, 2021 at 1:37

1 Answer 1

2

You should tweak it a bit, to be:

def Concat(url, x):
    for i in x:
        if i == 1:
            df1 = pd.read_json(url)
        else:
            df2 = pd.read_json(url)
            df3 = pd.concat([df1, df2], ignore_index=True)


def main():
    Concat('*url*', [1, 2])
Sign up to request clarification or add additional context in comments.

6 Comments

Comments and answer make sense - I understand why I'm getting the error. Just to make sure I understand the Answer, does Concat run twice from main(), once with x=1 and once with x=2?
@FlybatRamirez Nope, now it doesn't, it runs once
Ah, I see, you pass a list - it didn't occur to me to do that. Quite elegant.
I've tested your code, however I'm still getting the same error = "UnboundLocalError: local variable 'df1' referenced before assignment". It turns out df1 never gets created at all, so x ==1 is never True for some reason.
@FlybatRamirez Well that is probably an issue with your other code you didn't show us, Not my code...
|

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.