3

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?

3 Answers 3

1

Check with

out = df.join(pd.DataFrame(df.pop('Coordinates').tolist(), index=df.index, columns=["X", "Y"]))
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the answer, it worked. Currently, it changes the name of the columns to 0 and 1, how can create those columns with specific names, e.g., X and Y?
I guess, I figured that out myself. Here is what I did out = df.join(pd.DataFrame(df.pop('Coordinates').tolist(), index=df.index, columns=["X", "Y"]))
@RaziIqbal you got it ~
0

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

Comments

0
df = pd.DataFrame(df.Coordinates.str.split(',',1).tolist(),
                                 columns = ['X','Y'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.