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

查看:27
本文介绍了根据列名重新排序 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 之后),则您需要进行不同的排序,但这与 Pandas 无关.

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天全站免登陆