如何将DataFrame中包含列表的列展开为多行?
入门机器学习
答题要点
import pandas as pd
# 原始数据:列表列
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'hobbies': [['reading', 'swimming'], ['coding'], ['music', 'sports', 'cooking']]
})
# explode展开列表列
df_exploded = df.explode('hobbies')
# name hobbies
# 0 Alice reading
# 0 Alice swimming
# 1 Bob coding
# 2 Charlie music
# 2 Charlie sports
# 2 Charlie cooking
# 重置索引
df_exploded = df.explode('hobbies').reset_index(drop=True)
# 展开多列
df = pd.DataFrame({
'name': ['Alice', 'Bob'],
'hobbies': [['reading', 'swimming'], ['coding', 'gaming']],
'scores': [[90, 85], [95, 88]]
})
# 依次展开多列
df_exploded = df.explode('hobbies').explode('scores').reset_index(drop=True)
# 展开后保持其他列
df_exploded = df.explode('tags', ignore_index=True)
# 展开前后对比
print(f"原始行数: {len(df)}, 展开后行数: {len(df_exploded)}")
# 展开空列表
df = pd.DataFrame({
'name': ['Alice', 'Bob', 'Charlie'],
'tags': [['tag1', 'tag2'], [], ['tag3']] # Bob的tags为空
})
df_exploded = df.explode('tags') # Bob这行会保留,tags为NaN
# 结合groupby反向操作(聚合回列表)
df_grouped = df_exploded.groupby('name')['hobbies'].apply(list).reset_index()
# 实际应用:电商订单明细
# 一个订单多个商品
orders = pd.DataFrame({
'order_id': [1, 2],
'customer': ['Alice', 'Bob'],
'items': [['Apple', 'Banana'], ['Orange', 'Grape', 'Kiwi']]
})
order_details = orders.explode('items').reset_index(drop=True)
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题