You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按\n分隔符或每3行拆分df列并保留拆分后索引

pandas 数据框拆分方案(保留原索引)

场景1:按\n拆分指定列

使用str.split+explode实现,拆分后对应行继承原有索引:

import pandas as pd

# 替换为你需要拆分的列名,示例列名为target_col
df = df.assign(target_col=df['target_col'].str.split('\n')).explode('target_col', ignore_index=False)

如果你的pandas版本低于1.3.0(不支持explode的ignore_index参数),可以用如下兼容写法:

# 拆分列并堆叠
split_series = df['target_col'].str.split('\n', expand=True).stack().reset_index(level=1, drop=True)
split_series.name = 'target_col'
# 关联回原表,自动匹配原索引
df = df.drop('target_col', axis=1).join(split_series)

场景2:按每3行拆分整个数据框

直接按行切片即可,切片操作不会修改原有行索引:

# 拆分后得到由多个3行子df组成的列表
sub_df_list = [df.iloc[i:i+3] for i in range(0, len(df), 3)]

如果需要给每个3行组加标记,方便后续分组操作,可新增分组列:

# 相同group_id值的行属于同一个3行组,原索引完全保留
df['group_id'] = df.index // 3

内容的提问来源于stack exchange,提问作者Amargitts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 13:54:08