how to append elements in a list in dataframe to elements in a list in another dataframe?
Question:
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]
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>
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]
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>