【问题标题】:Re-arrange DataFrame columns based on a list of names根据名称列表重新排列 DataFrame 列
【发布时间】:2021-05-19 11:51:52
【问题描述】:

我的问题总结:我有许多 DataFrame,所有列都具有相同的列,但每次都以不同的顺序排列(即 df1 有它的顺序,df2 有另一个顺序,df3 有另一个顺序等等......)。我想根据作为基准的列列表来排列每个 DataFrame 中的列。因此,基于此列表,所有数据框都应具有相同的列顺序。

更详细的描述:我的代码中有几个数据帧是通过清理一些数据集产生的。这些 DataFrame 中的每一个都有相同的列,但顺序不同。例如:

DataFrame1 'rank' 'title' 'summary' 'date' 'image' 'id' 'description'

DataFrame2 'date' 'rank' 'title' 'description' 'image' 'summary' 'id'

DataFrame3 'id' 'description' 'summary' 'date' 'rank' 'image' 'title'

我有一个列名列表,我想将其用作对所有 DataFrame 中的列进行排序的参考,例如 'title' 'date' 'rank' 'image' 'description' 'summary' 'id'

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

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    将您想要的订单保存到一个列表中,例如list_cols,如下所示:

    list_cols = ['title', 'date', 'rank', 'image', 'description', 'summary', 'id']
    

    然后按如下方式更改数据框的列:

    df1 = df1[list_cols]
    df2 = df2[list_cols]
    df3 = df3[list_cols]
    

    【讨论】:

    • 太棒了!然后,您可以接受答案(在投票部分下方打勾)以确认它是解决方案
    【解决方案2】:

    首先选择你想要的列顺序。

    col_order = ['title', 'date', 'rank', 'image', 'description', 'summary', 'id']
    

    现在您可以使用 reindex 方法将此顺序分配回每个 Dataframe。

    df1_ordered = df1.reindex(columns = col_order)
    df2_ordered = df2.reindex(columns = col_order)
    df3_ordered = df3.reindex(columns = col_order)
    

    【讨论】:

    • 感谢您的回复!这似乎还可以,但@Ishwar 的回答似乎更直接。
    猜你喜欢
    • 2021-12-26
    • 2021-09-30
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2021-05-19
    相关资源
    最近更新 更多