I need to append a row to pandas dataframe inside a function and using the values that are passed as arguments.
import pandas as pd
# Declare global DataFrame
global df
df = pd.DataFrame([['1','2','3']], columns=['x','y','z'])
def append_row(a,b,c):
vlist = [a,b,c]
cols = ['x','y','z']
# using zip() to convert lists to dictionary
res = dict(zip(cols, vlist))
# Create pandas DataFrame for new row addition
df = df.append(res, ignore_index=True)
print("New row added", df.tail(1))
return df
Expected Output:
New row appended to `df`
x y z
1 2 3
a b c
When I run this code, I get an:
Python 3: UnboundLocalError: local variable `df` referenced before assignment.
How would I be able to modify pandas DataFrame and add a new row by referencing a dataframe that's read outside the function?
Additional context: The function is called/invoked from a different script and the DataFrame is read in the same script as function declaration.