如何拆分Python Pandas数据框行内的列表为多行?
问题:展开DataFrame中的列表列
以下是构造数据框的代码:
import pandas as pd # create a list product_list = ["bag","necklece"] sold__commentlist = [['nice to use',"bad"],["good",'can be improved']] # dataframe data = pd.DataFrame (columns = ['product','sold_comment']) # plug the list into the dataframe data['product'] = product_list data ['sold_comment'] = sold__commentlist data
构造得到的数据框:
product sold_comment 0 bag [nice to use, bad] 1 necklace [good, can be improved]
需要将其转换为如下形式:
product sold_comment 0 bag nice to use 0 bag bad 1 necklace good 1 necklace can be improved
解决方案
可以使用Pandas内置的explode()方法,专门用来展开包含列表的列,同时保留原始行的索引:
# 展开sold_comment列 expanded_data = data.explode('sold_comment') print(expanded_data)
执行后输出结果即为目标格式:
product sold_comment 0 bag nice to use 0 bag bad 1 necklace good 1 necklace can be improved
如果你的Pandas版本低于0.25.0(explode()方法在该版本才引入),可以用以下兼容写法:
# 兼容旧版本Pandas的实现 expanded_data = data.set_index('product')['sold_comment'].apply(pd.Series).stack().reset_index(name='sold_comment').drop('level_1', axis=1) print(expanded_data)
内容的提问来源于stack exchange,提问作者KiuSandy
相关产品推荐
相关产品推荐

