如何指定列列表将多列移至Pandas DataFrame末尾
移动指定列到Pandas DataFrame末尾
原DataFrame
index a b c 1 2 3 4 2 3 4 5
需求
指定列列表 l = ['a', 'b'],将这两列移至DataFrame末尾,无需手动指定所有列。
解决方案
通过筛选出不需要移动的列,再将其与目标列拼接成新的列顺序,重新索引DataFrame即可:
import pandas as pd # 构造原DataFrame df = pd.DataFrame({'a': [2, 3], 'b': [3, 4], 'c': [4, 5]}, index=[1, 2]) # 指定要移动的列 l = ['a', 'b'] # 获取无需移动的列 remaining_cols = [col for col in df.columns if col not in l] # 重新排列列顺序 df = df[remaining_cols + l]
执行结果
index c a b 1 4 2 3 2 5 3 4
内容的提问来源于stack exchange,提问作者user308827
相关产品推荐
相关产品推荐

