0

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

2
  • 1
    df2['full'][index]= l command works when there already is a column named 'full'. First we need to create it. df2['full'] = "" in the beginning Commented Dec 28, 2022 at 11:07
  • It is also possible to just add the columns, provided null values are replaced with empty lists. Commented Dec 29, 2022 at 5:35

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.