close

How can I split a column of tuples in a Pandas dataframe?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How can I split a column of tuples in a Pandas dataframe in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How can I split a column of tuples in a Pandas dataframe?

  1. How can I split a column of tuples in a Pandas dataframe?

    You can do this by doing pd.DataFrame(col.tolist()) on that column:
    In [2]: df = pd.DataFrame({'a':[1,2], 'b':[(1,2), (3,4)]})

  2. split a column of tuples in a Pandas dataframe

    You can do this by doing pd.DataFrame(col.tolist()) on that column:
    In [2]: df = pd.DataFrame({'a':[1,2], 'b':[(1,2), (3,4)]})

Method 1

You can do this by doing pd.DataFrame(col.tolist()) on that column:

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

In [3]: df
Out[3]:
   a       b
0  1  (1, 2)
1  2  (3, 4)

In [4]: df['b'].tolist()
Out[4]: [(1, 2), (3, 4)]

In [5]: pd.DataFrame(df['b'].tolist(), index=df.index)
Out[5]:
   0  1
0  1  2
1  3  4

In [6]: df[['b1', 'b2']] = pd.DataFrame(df['b'].tolist(), index=df.index)

In [7]: df
Out[7]:
   a       b  b1  b2
0  1  (1, 2)   1   2
1  2  (3, 4)   3   4

Note: in an earlier version, this answer recommended to use df['b'].apply(pd.Series) instead of pd.DataFrame(df['b'].tolist(), index=df.index)

Method 2

I think a simpler way is:

>>> import pandas as pd
>>> df = pd.DataFrame({'a':[1,2], 'b':[(1,2), (3,4)]})
>>> df
   a       b
0  1  (1, 2)
1  2  (3, 4)
>>> df['b_a'] = df['b'].str[0]
>>> df['b_b'] = df['b'].str[1]
>>> df
   a       b  b_a  b_b
0  1  (1, 2)    1    2
1  2  (3, 4)    3    4

Conclusion

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read