Home > front end >  Append rows as new columns in another dataframe pandas/python
Append rows as new columns in another dataframe pandas/python

Time:10-17

I have a for loop iterating over rows in an input dataframe. For each row a search is made. The output returns 5 rows and I would like to append these rows as new columns of the input dataframe.

    duplicate_materials  
0  [BIAS CUT FABRIC 50 X 1600 MM, RBN20 (000000000001065341)]   
1  [BIAS CUT FABRIC 40 X 1600 MM, RBN20 (000000000001061715)]   
2  [BIAS CUT  FABRIC 40 X 1100 MM, RBN20 (000000000001059946)]  
3  [BIAS CUT FABRIC 40 X 1200 MM, RBN20 (000000000001059947)]   
4  [BIAS CUT  FABRIC 50 X 1300 MM (000000000001005101)] 

These 5 rows should be appended as 5 new columns to the searched row in the input dataframe. In the following dataframe, the above 5 rows should be listed behind the first column to showcase that this was the result of the search.

material_id material_description    duplicate_materials_0   duplicate_materials_1   duplicate_materials_2   duplicate_materials_3   duplicate_materials_4
1   000000000001065341  FABRIC CUT BIAS, RBN20 50 X 1600 MM 

Edit: Solved by

for i, row in results.iterrows():
df_test[f'duplicate_materials_{i}'] = results['duplicate_materials'][i]

    

CodePudding user response:

Is the duplicate_materials column is of dtype object? This is necessary in order to insert lists into single cells. You can check with this command:

df.dtypes

If not, you can set the dtype manually.

df['duplicate_materials'] = df['duplicate_materials'].astype('object')

More details: Python pandas insert list into a cell

P.S. You mention using a for-loop to iterate over rows. Maybe this can be avoided by applying the search operation to the whole dataframe.

  • Related