how to append elements in a list in dataframe to elements in a list in another dataframe?

Question:

I want to append values of a column in df1 append to values of a column in df2 and the same as for the ‘b’ column. the result should be:

enter image description here

Asked By: mohammad

||

Answers:

Use pd.combine for this:

df1 = pd.DataFrame({
    'a' : [[*range(5)]],
    'b' : [[*range(5,10)]]
})
df2 = pd.DataFrame({
    'a' : [[*range(11,14)]],
    'b' : [[*range(22,25)]]
})

result = df1.combine(df2, lambda x, y: x + y)

Output result:

                             a                            b
0  [0, 1, 2, 3, 4, 11, 12, 13]  [5, 6, 7, 8, 9, 22, 23, 24]
Answered By: Rabinzel

Finaly, I have a dataframe that some of its cells have multiple lists:

df1 a b
0 [0,2,3][4,3][7,5,4,3] [3,4,5,6,7]
after printing, it is enclosed in str quotes:
‘[0,2,3][4,3][7,5,4,3]’ ‘[3,4,5,6,7]’
I want to merge list in a column into one:
[0,2,3,4,3,7,5,4,3]
but after running tcs.applymap(ast.literal_eval), I get error:
ValueError: malformed node or string: <_ast.Subscript object at 0x7fef5aa90610>
enter image description here

Answered By: mohammad
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.