Menu Close

How to split a column of tuples in a Python Pandas data frame?

Sometimes, we want to split a column of tuples in a Python Pandas data frame.

In this article, we’ll look at how to split a column of tuples in a Python Pandas data frame.

How to split a column of tuples in a Python Pandas data frame?

To split a column of tuples in a Python Pandas data frame, we can use the column’s tolist method.

For instance, we write:

import pandas as pd

df = pd.DataFrame({'a': [1, 2], 'b': [(1, 2), (3, 4)]})
df2 = pd.DataFrame(df['b'].tolist(), index=df.index)
print(df2)

We create the df data frame with the pd.DataFrame class and a dictionary.

Then we create a new data frame from df by using df['b'].tolist() to get column b and convert it to a list.

And we set the index to df.index.

This will split the tuple elements into separate entries in each row.

Therefore, df2 is:

   0  1
0  1  2
1  3  4

Conclusion

To split a column of tuples in a Python Pandas data frame, we can use the column’s tolist method.

Posted in Python, Python Answers