如何按条件在Pandas DataFrame中向上移动指定行?
调整DataFrame行顺序:将'Match'为'Yes'的行上移一行
原始DataFrame
import pandas as pd data = [['Construction', '', '01/02/2022', '01/06/2022', '1', 'No'], ['Level Site', 'Construction', '01/02/2022', '01/02/2022', '2', 'No'], ['Foundation', '', '01/03/2023', '01/06/2023', '1', 'Yes'], ['Lay Foundation', 'Construction>Foundation', '01/03/2022', '01/04/2022', '3', 'No'], ['Prepare land for foundation', 'Construction>Foundation', '01/05/2022', '01/06/2022', '3', 'No'], ['Building Envelope', '', '01/07/2023', '01/16/2023', '1', 'No'], ['Install Footings', 'Building Envelope', '01/07/2022', '01/07/2022', '2', 'Yes'], ['Pouring', '', '01/08/202', '01/09/2023', '1', 'No'], ['Pour Foundation', 'Building Envelope>Pouring', '01/08/2022', '01/09/2022', '3', 'No'], ['Installation', '', '01/09/2022', '01/14/2022', '1', 'No']] df1 = pd.DataFrame(data, columns=['Activity', 'Parent', 'Start', 'Finish', 'WBS Level', 'Match'])
期望输出的DataFrame
data = [['Construction', '', '01/02/2022', '01/06/2022', '1', 'No'], ['Foundation', '', '01/03/2023', '01/06/2023', '1', 'Yes'], ['Level Site', 'Construction', '01/02/2022', '01/02/2022', '2', 'No'], ['Lay Foundation', 'Construction>Foundation', '01/03/2022', '01/04/2022', '3', 'No'], ['Prepare land for foundation', 'Construction>Foundation', '01/05/2022', '01/06/2022', '3', 'No'], ['Install Footings', 'Building Envelope', '01/07/2022', '01/07/2022', '2', 'Yes'], ['Building Envelope', '', '01/07/2023', '01/16/2023', '1', 'No'], ['Pouring', '', '01/08/202', '01/09/2023', '1', 'No'], ['Pour Foundation', 'Building Envelope>Pouring', '01/08/2022', '01/09/2022', '3', 'No'], ['Installation', '', '01/09/2022', '01/14/2022', '1', 'No']] df2 = pd.DataFrame(data, columns=['Activity', 'Parent', 'Start', 'Finish', 'WBS Level', 'Match'])
需求说明
为调度软件准备数据时,需要将所有Match列值为Yes的行向上移动一行,且不能删除或覆盖任何行。
解决方案
通过定位目标行索引,从后往前交换目标行与前一行的位置,避免索引混乱:
# 获取所有Match为Yes的行索引 yes_indices = df1[df1['Match'] == 'Yes'].index.tolist() # 从后往前处理索引,防止交换后索引错位 for idx in reversed(yes_indices): # 排除第一行,避免索引越界 if idx > 0: # 交换当前行和前一行的位置 df1.iloc[[idx-1, idx]] = df1.iloc[[idx, idx-1]].values # 验证结果 print(df1)
关键说明
- 反向处理索引:如果先处理靠前的索引,交换操作会改变后续目标行的位置,导致错误。从后往前处理能避免这个问题。
- 直接行交换:通过
iloc定位两行并交换值,确保所有数据完整保留,无丢失或覆盖。
内容的提问来源于stack exchange,提问作者bcoder
相关产品推荐
相关产品推荐

