I have a series of tuples of the form ('Name', Number)
, and I would like to split them into two columns, one being the name, the other being the number.
I’d like to end up with something like this:
JavaScript
x
5
1
Tuple Name Number
2
('Scott Smith', 56) Scott Smith 56
3
('Anna Frank', 100) Anna Frank 100
4
('Seth Morris', 32) Seth Morris 32
5
I’ve tried a few iterations of splitting strings, applying a lambda function, etc, and can’t seem to get this simple process right.
Advertisement
Answer
Construct a new dataframe and assign back to dataframe
sample df
:
JavaScript
1
13
13
1
Tuple
2
0 (Scott Smith, 56)
3
1 (Anna Frank, 100)
4
2 (Seth Morris, 32)
5
6
df_final = df.assign(**pd.DataFrame(df.Tuple.tolist(), columns=['Name','Number']))
7
8
Out[170]:
9
Tuple Name Number
10
0 (Scott Smith, 56) Scott Smith 56
11
1 (Anna Frank, 100) Anna Frank 100
12
2 (Seth Morris, 32) Seth Morris 32
13