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

如何在Pandas DataFrame中仅对特定行子集进行排序?

如何仅对DataFrame中is_plane == False的行子集排序并保留True行的原始位置?

原始DataFrame

Plane PartsQuantityis_plane
G6_32 FAB1True
G6_32 KIT2True
Item D2False
Item C4False
Item A5False
G6_32 SITE5True
G6_32 SPACE6True
Item C2False
Item A1False
Item F2False

需求说明

仅对is_plane == False的连续行块进行排序,is_plane == True的行必须保持原始位置不变,最终得到目标DataFrame。

解决方案

利用pandas的cumsum生成分组键,结合groupby对不同行块进行针对性处理:

import pandas as pd

# 构造原始DataFrame
data = {
    'Plane Parts': ['G6_32 FAB', 'G6_32 KIT', 'Item D', 'Item C', 'Item A', 
                    'G6_32 SITE', 'G6_32 SPACE', 'Item C', 'Item A', 'Item F'],
    'Quantity': [1, 2, 2, 4, 5, 5, 6, 2, 1, 2],
    'is_plane': [True, True, False, False, False, True, True, False, False, False]
}
df = pd.DataFrame(data)

# 生成分组键:用True行作为分隔,将连续的False行划分为独立组
df['group_key'] = df['is_plane'].cumsum()

# 分组处理:False组按Plane Parts升序排序,True组直接保留原顺序
result = df.groupby('group_key', group_keys=False).apply(
    lambda x: x.sort_values('Plane Parts') if not x['is_plane'].any() else x
)

# 清理临时列并重置索引
result = result.drop(columns='group_key').reset_index(drop=True)

# 输出结果
print(result)

结果验证

运行后得到的结果与目标一致:

Plane PartsQuantityis_plane
G6_32 FAB1True
G6_32 KIT2True
Item A5False
Item C4False
Item D2False
G6_32 SITE5True
G6_32 SPACE6True
Item A1False
Item C2False
Item F2False

原理说明

  • df['is_plane'].cumsum():由于True在数值运算中等同于1,False等同于0,累加后会为每个连续的False行块分配唯一的分组键,True行也会各自成组。
  • groupby分组后,针对每组判断是否包含True行:不包含的(纯False组)执行排序,包含的(True组)直接保留原始顺序,从而实现需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:50:25