Reputation: 115
I have a pandas dataframe like shown below where the coordinates column contains X and Y coordinates:
Coordinates Cluster
0 [25, 79] 2
1 [34, 51] 2
2 [22, 53] 2
3 [27, 78] 2
4 [33, 59] 2
I want to split the Coordinates column into X and Y column so that I have something like below:
X Y Cluster
0 25 79 2
1 34 51 2
2 22 53 2
3 27 78 2
4 33 59 2
How can I achieve this?
Upvotes: 3
Views: 1481
Reputation: 237
df = pd.DataFrame(df.Coordinates.str.split(',',1).tolist(),
columns = ['X','Y'])
Upvotes: 0
Reputation: 28729
You could dump it into numpy as well :
df = pd.DataFrame(
{
"Coordinates": [[25, 79], [34, 51], [22, 53], [27, 78], [33, 59]],
"Cluster": [2, 2, 2, 2, 2],
})
box = df.to_numpy()
pd.DataFrame(np.column_stack([np.vstack(box[:, 0]), box[:, -1]]),
columns=["X", "Y", "Cluster"])
X Y Cluster
0 25 79 2
1 34 51 2
2 22 53 2
3 27 78 2
4 33 59 2
Upvotes: 0
Reputation: 323396
Check with
out = df.join(pd.DataFrame(df.pop('Coordinates').tolist(), index=df.index, columns=["X", "Y"]))
Upvotes: 1