Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading