如何在Pandas DataFrame中重排指定行子集并放回原位置?
嘿,这个问题我之前也碰到过!核心问题就是Pandas的赋值会默认匹配索引,导致你直接用带索引的子集赋值时出现不匹配的情况。这里有两种通用的解决方案,对应你不同的需求场景:
方案1:只替换值,保持原行索引不变
如果你只是想把原子集里的行按新顺序的值放回原位置,而不改变行索引本身(比如原位置2的值变成原行4的值,行索引还是2),可以直接提取重排后子集的values来赋值:
import pandas as pd import numpy as np # 初始DataFrame df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21]]), columns=['a', 'b', 'c']) # 定义子集的位置索引(iloc用的位置)和新顺序 subset_positions = [2, 3, 4, 5] new_subset_order = [2, 0, 1, 3] # 提取子集并按新顺序重排 reordered_subset = df.iloc[subset_positions].iloc[new_subset_order] # 用.values跳过索引匹配,直接赋值值 df.iloc[subset_positions] = reordered_subset.values print(df)
输出结果(行索引保持原顺序,值按要求替换):
a b c 0 1 2 3 1 4 5 6 2 13 14 15 3 7 8 9 4 10 11 12 5 16 17 18 6 19 20 21
方案2:移动行,保留原行索引(完全匹配你想要的Out[2])
如果你希望直接把原行按新顺序移动到目标位置,保留原行索引(比如原行4直接移到原位置2,行索引还是4),可以构造完整的行索引列表后重新索引:
import pandas as pd import numpy as np df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18], [19, 20, 21]]), columns=['a', 'b', 'c']) # 定义子集的行索引(不是位置)和新顺序 subset_indices = [2, 3, 4, 5] new_subset_order = [2, 0, 1, 3] # 构造重排后的子集索引 reordered_subset_indices = [subset_indices[i] for i in new_subset_order] # 构造完整的新行索引列表 new_full_indices = df.index[:2].tolist() + reordered_subset_indices + df.index[6:].tolist() # 重新索引整个DataFrame df = df.reindex(new_full_indices) print(df)
输出结果和你期望的Out[2]完全一致:
a b c 0 1 2 3 1 4 5 6 4 13 14 15 2 7 8 9 3 10 11 12 5 16 17 18 6 19 20 21
为什么你的原方法失败?
当你执行df.iloc[idx] = df.iloc[idx].reindex(idx2[i]).reset_index(drop=True)时,reset_index(drop=True)会把右侧的索引变成0-3,但左侧df.iloc[idx]对应的原行索引是2-5,Pandas会尝试把右侧索引0对应左侧索引2,1对应3,以此类推,这就导致了值的错位。而用.values或者构造完整行索引的方式,就绕过了索引匹配的逻辑,直接按位置赋值或重排。
这两种方案都能适配不同的子集和新顺序,只需要修改对应的subset_positions/subset_indices和new_subset_order即可。
内容的提问来源于stack exchange,提问作者myradio
相关产品推荐
相关产品推荐

