DataFrames 列根据列表重新排列 - DataFrames 有不同的列

DataFrames columns re-arrange based on list - DataFrames have different columns

SUMMARY of my problem:

More detailed description:

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

DataFrame1 'id', 'title', 'date', 'category', 'type', 'description', 'secondary category'

DataFrame2 'id', 'description', 'title', 'type', 'category', 'date'

DataFrame3 'id', 'category', 'description', 'title'

DESIRED OUTPUT:

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

DataFrame1 'id', 'title', 'type', 'category', 'secondary category', 'date', 'description'

DataFrame2 'id', 'title', 'type', 'category', 'date', 'description'

DataFrame3 'id', 'title', 'category', 'description'

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

您可以使用列表理解对列的顺序进行排序并使用 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)