Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expand a column of lists into multiple rows in Pandas

I have a Pandas dataframe where one of the columns is a list. I'd like to expand this list.

How can I do this?

Begin with:

0 [{ first: 'jon', last: 'McSmith' }, { first: 'Jennifer', last: 'Foobar'}]
1 [{ first: 'dan', last: 'Raizman' }, { first: 'Alden', last: 'Lowe'}]

Name: players, dtype: object

End with:

   first         last
--------------------------
0  Jon           McSmith
1  Jennifer      Foobar
2  Dan           Raizman
3  Alden         Lowe
like image 600
Don P Avatar asked Mar 02 '23 02:03

Don P


1 Answers

Use np.hstack to stack the lists in column players horizontally and create a new dataframe :

df1 = pd.DataFrame(np.hstack(df['players']).tolist())

Or use Series.explode (available in pandas version >= 0.25),

df1 = pd.DataFrame(df['players'].explode().tolist())

Another option using itertools.chain as suggested by @cs95

from itertools import chain

df1 = pd.DataFrame(chain.from_iterable(df['players']))

Result:

print(df1)

      first     last
0       jon  McSmith
1  Jennifer   Foobar
2       dan  Raizman
3     Alden     Lowe
like image 114
Shubham Sharma Avatar answered Mar 04 '23 17:03

Shubham Sharma