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

如何将Pandas DataFrame中相同的行归置在一起?

问题解答

这个需求完全可以实现,核心是让相同model+lot组合的行连续排列,以下是两种简单的实现方式:

方式1:直接排序(最简便)

通过sort_values按model和lot列排序,就能快速将同组合的行集中:

import pandas as pd

df = pd.DataFrame({'model':['A','A','A','B', 'B','B','C','C','C','C'],
                   'lot':['x','x','y','y', 'y','y','y','y','z','z'],
                   'qty':[1,2,1,3,1,4,3,2,2,2]})

# 按model、lot排序,同时重置索引
df_result = df.sort_values(by=['model', 'lot'], ignore_index=True)
print(df_result)

方式2:分组拼接(逻辑更直观)

如果想明确体现分组过程,可以先按model和lot分组,再把各组数据拼接起来:

import pandas as pd

df = pd.DataFrame({'model':['A','A','A','B', 'B','B','C','C','C','C'],
                   'lot':['x','x','y','y', 'y','y','y','y','z','z'],
                   'qty':[1,2,1,3,1,4,3,2,2,2]})

# 分组后收集各组,再拼接
group_list = [group for _, group in df.groupby(['model', 'lot'])]
df_result = pd.concat(group_list, ignore_index=True)
print(df_result)

最终效果

两种方法得到的结果一致,结构如下:

modellotqty
Ax1
Ax2
Ay1
By3
By1
By4
Cy3
Cy2
Cz2
Cz2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 15:32:21