Poonam
Poonam

Reputation: 679

Not able to append dataframe

I am not able to append dataframe to already created dataframe.
Expecting output as below:

a    b  

0 1 1
1 2 4
2 11 121
3 12 144

import pandas

def FunAppend(*kwargs):
    if len(kwargs)==0:
        Dict1={'a':[1,2],'b':[1,4]}
        df=pandas.DataFrame(Dict1)
    else:

        Dict1={'a':[11,12],'b':[121,144]}       
        dfTemp=pandas.DataFrame(Dict1)
        df=df.append(dfTemp,ignore_index=True)
    return df


df=FunAppend()
df=FunAppend(df)
print df
print "Completed"

Any help would be appreciated.

Upvotes: 0

Views: 167

Answers (2)

omri_saadon
omri_saadon

Reputation: 10631

As df is not defined when you go to the else case, although you did sent the df to the function in the form of kwargs, so you can access to the df by typing kwargs[0]

Change this:

df=df.append(dfTemp,ignore_index=True)

To:

df=kwargs[0].append(dfTemp,ignore_index=True)

Upvotes: 1

fafl
fafl

Reputation: 7385

You are modifying the global variable df inside the FunAppend function.

Python needs to be explicitly notified about this. Add inside the function:

global df

And it works as expected.

Upvotes: 3

Related Questions