Python Pandas按固定词数拆分字符串列为多行且其余列保留实现
实现方案
你的原有代码存在两个问题:
- apply作用于整个DataFrame的所有列,而非仅需要拆分的
package_code列 - 没有将
group_words返回的生成器转换为列表,导致最终输出为生成器对象而非拆分后的文本内容
你可以通过「对目标列单独生成分组列表 + explode拆分为多行」的方式实现需求,完整代码如下:
import pandas as pd # 示例数据 df = pd.DataFrame({ "order_id":[1,3,7], "order_date":["20/5/2018","22/5/2018","23/5/2018"], "package":["p1","p4","p5,p6"], "package_code":["As he crossed toward the pharmacy at the","he was dancing in the","they were playing football"] }) # 分组拆分函数 def group_words(s, n): words = s.split() for i in range(0, len(words), n): yield ' '.join(words[i:i+n]) # 第一步:将package_code列每个值转成分组后的列表 n = 5 # 每5个词一组 df['package_code'] = df['package_code'].apply(lambda x: list(group_words(x, n))) # 第二步:将列表拆分为多行,其余列值自动复用原行内容 df = df.explode('package_code', ignore_index=True) print(df)
运行结果
order_id order_date package package_code 0 1 20/5/2018 p1 As he crossed toward the 1 1 20/5/2018 p1 pharmacy at the 2 3 22/5/2018 p4 he was dancing in the 3 7 23/5/2018 p5,p6 they were playing football
如果你的pandas版本低于0.25不支持explode,可使用如下兼容写法:
df = df.set_index(['order_id', 'order_date', 'package'])['package_code'].apply(pd.Series).stack().reset_index(drop=True, level=-1).reset_index(name='package_code')
内容的提问来源于stack exchange,提问作者user2543622
相关产品推荐
相关产品推荐

