如何将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)
最终效果
两种方法得到的结果一致,结构如下:
| model | lot | qty |
|---|---|---|
| A | x | 1 |
| A | x | 2 |
| A | y | 1 |
| B | y | 3 |
| B | y | 1 |
| B | y | 4 |
| C | y | 3 |
| C | y | 2 |
| C | z | 2 |
| C | z | 2 |
内容的提问来源于stack exchange,提问作者ghost_like
相关产品推荐
相关产品推荐

