Home > Back-end >  unable to add a new column to a pandas dataframe from within a function
unable to add a new column to a pandas dataframe from within a function

Time:12-29

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

CodePudding user response:

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

CodePudding user response:

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
  • Related