首页 > 解决方案 > 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

标签: pythonpandasdataframe

解决方案


用于水平np.hstack堆叠列中的列表players并创建一个新的数据框:

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

或者使用Series.explode(在 pandas 版本中可用 >= 0.25),

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

itertools.chain@cs95 建议使用的另一个选项

from itertools import chain

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

结果:

print(df1)

      first     last
0       jon  McSmith
1  Jennifer   Foobar
2       dan  Raizman
3     Alden     Lowe

推荐阅读