unable to add a new column to a pandas dataframe from within a function

it_json are columns that contain lists, for each row in a dataframe I want to add the lists
in a fresh column called full

def list_columns(df):
    df2=df.copy()
    for index,row in df.iterrows():
        # print(row)
        l=[]
        if row['it_json_1']:
            l+=row['it_json_1']
        if row['it_json_2']:
            l+=row['it_json_2']
        if row['it_json_3']:
            l+=row['it_json_3']
        if row['it_json_4']:
            l+=row['it_json_4']
        df2['full'][index]= l
    return df2

but list_columns(df) is giving me key error
enter image description here

>Solution :

Try to save the values into a list then assign them to the new columns "full"

 full.append(l)

then after the loop ends:

 df2['full'] = full

Leave a Reply