Python ValueError: Inserting a list of values using df.loc
I have a dataframe df with paths of images. I am performing object detection and want to save the names of the detected objects in a new column (named objects) of the dataframe.
However the code works fine when only 1 object is detected, when there is a list of multiple objects the code gives an error.
ValueError: cannot set using a multi-index selection indexer with a different length than the value
I think there is some problem with my way of inserting values in the dataframe. I have actually created an empty column first and then using loop inserting vaues in the objects column.
Code
train_image_paths = 'data/train_images/' + df['image']    # train_images is the folder containing images and 
                                                          #  df['image'] contains all image paths

df['objects'] = ''     # Creating an empty column for storing detected objects

for idx, img in enumerate(train_image_paths):
    ..
    #object detection code    # Performs object detection and 
                              # stores the detected objects in a list named detected_objects
    ..
    
    df.loc[idx, 'objects'] = detected_objects   # Adding the detected objects to the dataframe
    
return df

Output of df.info()
&lt;class 'pandas.core.frame.DataFrame'&gt;
RangeIndex: 34250 entries, 0 to 34249
Data columns (total 1 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   image   34250 non-null  object
dtypes: object(1)
memory usage: 267.7+ KB


I think you should create new list or Pandas Series then append it to dataframe.
train_image_paths = 'data/train_images/' + df['image']    # train_images is the folder containing images and 
                                                          #  df['image'] contains all image paths

objects = []     # Creating an empty column for storing detected objects

for idx, img in enumerate(train_image_paths):
    ..
    #object detection code    # Performs object detection and 
                              # stores the detected objects in a list named detected_objects
    ..
    
    objects.append(detected_objects)   # Adding the detected objects to the dataframe


df['objects'] = objects
return df

Here is the references: https://www.geeksforgeeks.org/adding-new-column-to-existing-dataframe-in-pandas/
