Pandas-如果列存在则重新排列列

问题描述 投票:0回答:1

我有一个混乱的数据帧,如果它们退出,如何重新排列列。

One      Two       Three  Six    Four     Five
1         2         3      6      4         5
1         2         3      6      4         5
...

如何排列此列?这里的问题是,六列可能并非在所有情况下都存在。因此,如果该列退出,我需要一条简单的行就可以按One Two Three Four Five Six的顺序进行排列。我的意思是,如果df中没有2,则应该为One Three Four Five Six

python pandas
1个回答
1
投票

用途:

 df1 = (df.reindex(['One', 'Two','Three','Four','Five','Six'], axis=1)
          .dropna(how='all', axis=1))

或:

c = ['One', 'Two','Three','Four','Five','Six']
df.columns = pd.CategoricalIndex(df.columns, categories=c, ordered=True)
df1 = df.sort_index(axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.