I have a dataframe df whose columns contains string representation of lists.
import pandas as pd
data = {'A': [['ABCD'], ['PQRS'], ['LMNOP']], 'B':[['YUIO', 'DFGH'], ['QWERT', 'CVDF', 'WERT'], ['BCLF', 'DASE', 'OPIU', 'RTYU']]}
df = pd.DataFrame(data)
df['A'] = df['A'].astype('str') #Intentionally added to mimic the actual problem.
df['B'] = df['B'].astype('str') #Intentionally added to mimic the actual problem.
df.head()
| A | B |
+------------+---------------------------------------+
| ['ABCD'] | ['YUIO', 'DFGH'] |
| ['PQRS'] | ['QWERT', 'CVDF', 'WERT'] |
| ['LMNOP'] | ['BCLF', 'DASE', 'OPIU', 'RTYU'] |
+------------+---------------------------------------+
I'm trying to merge list in column A with list in column B using the below code. However, this results in an output that is not expected.
df['B'] = df['A'] + df['B']
| A | B |
+------------+-----------------------------------------------+
| ['ABCD'] | ['ABCD']['YUIO', 'DFGH'] |
| ['PQRS'] | ['PQRS']['QWERT', 'CVDF', 'WERT'] |
| ['LMNOP'] | ['LMNOP']['BCLF', 'DASE', 'OPIU', 'RTYU'] |
+------------+-----------------------------------------------+
However, I'm expecting the output like below - which is something I'm unable to get using the above.
| A | B |
+------------+-----------------------------------------------+
| ['ABCD'] | ['ABCD', 'YUIO', 'DFGH'] |
| ['PQRS'] | ['PQRS', 'QWERT', 'CVDF', 'WERT'] |
| ['LMNOP'] | ['LMNOP', 'BCLF', 'DASE', 'OPIU', 'RTYU'] |
+------------+-----------------------------------------------+
Is there a way wherein I can merge two columns of string representation of lists and get an output like above ?