python - 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
解决方案
用于水平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
推荐阅读
- sql - 由于“ORDER BY”在视图定义中不起作用,我们如何在 db2 视图中对数据进行排序?
- javascript - Rails,webpacker:在哪里/何时在类中使用 import 语句,以及在 pack/application.js 中要求的目的是什么?
- reactjs - 手动部署收到错误“app.json 必须包含 JSON 对象”
- jenkins - Jenkins 作业无法将 tar 文件推送到 s3 存储桶
- python - 如何从python中的同一个大列表中制作项目对
- python - 如何使用 Selenium 抓取 innerHTML 以获取 NFL 投注数据?
- javascript - 在 vue js 中监听 $emit 并在处理程序中使用 value 以及 parent 的 value
- kotlin - Kotlin 活动重启
- java - Android api29 如何在安装时在主屏幕上自动添加应用程序图标?
- python - 如何使用 matplotlib 绘制一条平行于 y = x 线的线?