1

I have a dataframe df containing tuples like below in Column A

|  ID      |  A         |
+----------+------------+
|0         |(1, [a])    |
|1         |(2, [a,b])  |
|2         |(3, [c,a,b])|
+----------+------------+

I want to split the tuples in the above df and want to see my new dataframe df like below.

|  ID      |  A         |    B     |
+----------+------------+----------+
|0         | 1          |  [a]     |
|1         | 2          |  [a,b]   |
|2         | 3          |  [c,a,b] |
+----------+------------+----------+

So, how can I split the tuple in the above dataframe df?

user3046211
  • 466
  • 2
  • 13
  • Many solutions, same like answer you can find [here](https://stackoverflow.com/a/55458565/2901002) – jezrael Jun 27 '22 at 09:57

1 Answers1

1

Use the str accessor, make sure to start with creating B to avoid losing the data in A:

df['B'] = df['A'].str[1]
df['A'] = df['A'].str[0]

alternative:

df[['A', 'B']] = pd.DataFrame(df['A'].to_list(), columns=['A', 'B'])

output:

   ID  A          B
0   0  1        [a]
1   1  2     [a, b]
2   2  3  [c, a, b]
mozway
  • 194,879
  • 13
  • 39
  • 75