Search code examples
pythonfunctiondataframeassign

DataFrame assign inside function


I have a question regarding the df assign function. When using this function i must input the column name without apostrophes. Why is this and can i circumvent it? See example below

df = pd.DataFrame(columns=['Grade'])
df['Grade'] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

df_temp = df.assign(Grade='Total')

def dummy(df, _g):
# if I write grade here then I get the expected result
    return df.assign(_g='Total')

# here I want grade to be assigned to total but it creats a new variable called _g
df_temp = dummy(df, 'Grade')

Solution

  • def dummy(df, _g):
        return df.assign(**{_g: 'Total'})