首页 > 解决方案 > DataFrames 列根据列表重新排列 - DataFrames 具有不同的列

问题描述

我的问题总结:

更详细的说明:

我的代码中有几个 DataFrame,它们是通过清理一些数据集生成的。这些 DataFrame 中的每一个都有不同数量的列,并且以不同的顺序排列,但列限于此列表:'id', 'title', 'type', 'category', 'secondary category', 'date', 'description'. 因此,此列表中的列最多为 7 个。例子:

数据框1'id', 'title', 'date', 'category', 'type', 'description', 'secondary category'

数据帧2'id', 'description', 'title', 'type', 'category', 'date'

数据帧3'id', 'category', 'description', 'title'

期望的输出:

我想根据初始列表对列进行排序'id', 'title', 'type', 'category', 'secondary category', 'date', 'description',即使列数不同。从上面的例子中,DataFrames 应该变成:

数据框1'id', 'title', 'type', 'category', 'secondary category', 'date', 'description'

数据帧2'id', 'title', 'type', 'category', 'date', 'description'

数据帧3'id', 'title', 'category', 'description'

有没有办法,例如循环,以这种方式排列列?

标签: pythonpandasdataframecolumnsorting

解决方案


您可以使用列表推导对列的顺序进行排序并用于reindex设置正确的顺序:

desired_order = ['id', 'title', 'type', 'category', 'secondary category', 'date', 'description']

df = df.reindex([i for i in desired_order if i in df.columns], axis=1)

推荐阅读