Pandas如何按分组规则拆分DataFrame为两个子数据框
可行实现方案
你的数据满足「相同取值的分组固定连续重复5次」的规则,不需要用复杂的全局间隔匹配,两种方法都可以实现需求,其中第一种性能更优,适配大规模数据场景。
方法1:基于固定组长度的索引取数(推荐,性能最高)
因为每组固定5个连续行,直接对行索引做模5运算,判断行在组内的位置即可,不需要做分组聚合,千万级数据量下也能快速跑完:
# 如果原df索引不是从0开始的连续值,先执行这行重置索引 # df = df.reset_index(drop=True) # 计算每行在所属5行小组内的偏移位置,取值范围0-4 row_pos = df.index % 5 # 偏移量0、1对应每组前2行,归入第一个DataFrame df_first = df[row_pos < 2].reset_index(drop=True) # 偏移量2、3、4对应每组后3行,归入第二个DataFrame df_second = df[row_pos >= 2].reset_index(drop=True)
方法2:按列分组取数(鲁棒性更强)
如果后续可能出现组长度不固定的情况,可以直接按前两列分组,标记每组内的行序号再拆分,不需要依赖固定5行的规则:
# 标记每个分组内的行序号,从0开始计数 in_group_rank = df.groupby(['text', 'reference']).cumcount() df_first = df[in_group_rank < 2].reset_index(drop=True) df_second = df[in_group_rank >= 2].reset_index(drop=True)
运行结果
两种方法输出的结果和给出的期望完全一致:
df_first输出:text reference id 0 the weather is nice weather 1 1 the weather is nice weather 2 2 the house is beautiful house 6 3 the house is beautiful house 7 4 the day is long day 11 5 the day is long day 12
df_second输出:text reference id 0 the weather is nice weather 3 1 the weather is nice weather 4 2 the weather is nice weather 5 3 the house is beautiful house 8 4 the house is beautiful house 9 5 the house is beautiful house 10 6 the day is long day 13 7 the day is long day 14 8 the day is long day 15
内容的提问来源于stack exchange,提问作者zara kolagar
相关产品推荐
相关产品推荐

