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
                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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With