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

Question:

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

Asked By: Sruthi

||

Answers:

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
Answered By: Maen

You are allocating values to a column that doesn’t exist yet, so create an empty column before adding values.

def list_columns(df):
df2=df.copy()
for index,row in df.iterrows():
    # print(row)
    l=[]
    l['full'] = np.nan
    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
Answered By: Saksham Sharma
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.