根据列名称对pandas数据框中的列进行重新排序 [英] Re-ordering columns in pandas dataframe based on column name

查看:83
本文介绍了根据列名称对pandas数据框中的列进行重新排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个超过200列的dataframe.问题是因为它们的生成顺序是

I have a dataframe with over 200 columns. The issue is as they were generated the order is

['Q1.3','Q6.1','Q1.2','Q1.1',......]

我需要按以下顺序重新排列列:

I need to re-order the columns as follows:

['Q1.1','Q1.2','Q1.3',.....'Q6.1',......]

我在Python中有什么方法可以做到这一点吗?

Is there some way for me to do this within Python?

推荐答案

df = df.reindex(sorted(df.columns), axis=1)

这假定对列名称进行排序将给出所需的顺序.如果您的列名不会按字典顺序排序(例如,如果您希望列Q10.3出现在Q9.1之后),则需要进行其他排序,但这与熊猫无关.

This assumes that sorting the column names will give the order you want. If your column names won't sort lexicographically (e.g., if you want column Q10.3 to appear after Q9.1), you'll need to sort differently, but that has nothing to do with pandas.

这篇关于根据列名称对pandas数据框中的列进行重新排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆