Home > other >  add a list to another list pandas
add a list to another list pandas

Time:06-13

Hi I need help with a problem with a dataframe like that:

df = pd.DataFrame({'column_A': [[{'zone':'A', 'number':'7'}, {'zone':'B', 'number': '8'}], 
                               [{'zone':'A', 'number':'6'}, {'zone':'E', 'number':'7'}]],
                   'column_B': [[{'zone':'C', 'number':'4'}], [{'zone':'D', 'number': '9'}]]})

I want to inset column_B in the column_A list so the output of the first line of column_A have to be:

[{'zone':'A', 'number':'7'}, {'zone':'B', 'number': '8'}, {'zone':'C', 'number':'4'}]

Probably is the easiest thing i can imagine but i find so many errors with functions like insert and ' ' command and I ran out of ideas.

Anyone knows the answer?

CodePudding user response:

Simpliest is join lists by :

df['column_A'] = df['column_A']   df['column_B']
print (df)
                                            column_A  \
0  [{'zone': 'A', 'number': '7'}, {'zone': 'B', '...   
1  [{'zone': 'A', 'number': '6'}, {'zone': 'E', '...   

                         column_B  
0  [{'zone': 'C', 'number': '4'}]  
1  [{'zone': 'D', 'number': '9'}]  

Data are different, seems in second column are not lists:

df = pd.DataFrame({'column_A': [[{'zone':'A', 'number':'7'}, {'zone':'B', 'number': '8'}], 
                               [{'zone':'A', 'number':'6'}, {'zone':'E', 'number':'7'}]],
                   'column_B': [{'zone':'C', 'number':'4'}, {'zone':'D', 'number': '9'}]})

df['column_A'] = df['column_A']   df['column_B'].apply(lambda x: [x])
print (df)
                                            column_A  \
0  [{'zone': 'A', 'number': '7'}, {'zone': 'B', '...   
1  [{'zone': 'A', 'number': '6'}, {'zone': 'E', '...   

                       column_B  
0  {'zone': 'C', 'number': '4'}  
1  {'zone': 'D', 'number': '9'}  
  • Related