python - DataFrames 列根据列表重新排列 - DataFrames 具有不同的列
问题描述
我的问题总结:
我有很多 DataFrame,所有的列都有相同的池(7 列,例如 COLUMN1:COLUMN7),但有时缺少一个或多个列(即 DataFrame 可能有 COLUMN1:COLUMN3 + COLUMN6:COLUMN7,因此第 4 列和第 5 列失踪)。
每个 DataFrame 每次都有以不同顺序排列的列(即 df1 有它的顺序,df2 有另一个顺序,df3 有另一个顺序等等......)。
我想根据用作基准的列列表(在本例中为从 1 到 7 的列列表)来排列每个 DataFrame 中的列。
期望的结果是所有数据框都具有基于此列表的相同列顺序,如果缺少列,则应保留顺序(即,如果缺少第 4 列和第 5 列,列的顺序应为:COL1, COL2、COL3、COL6、COL7)。
更详细的说明:
我的代码中有几个 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'
有没有办法,例如循环,以这种方式排列列?
解决方案
您可以使用列表推导对列的顺序进行排序并用于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)
推荐阅读
- python - 我可以在dict中获取列表项吗?
- r - 与 geom_image 和 PNG 包结合使用时,geom_mark_hull 绘图不正确
- javascript - for循环模式不传递信息
- amazon-web-services - AWS Managed Airflow 将文件夹上传到 MWAA 环境
- java - 如何在不使用 android 10 中的 READ_PHONE_STATE 权限的情况下获取网络连接类型?
- python - python中的错误:'list'对象没有属性'shape'
- python - AttributeError:“Paddle”对象没有“screen”属性。你的意思是:'_screen'?
- excel - 使用查找表对值求和,其中查找值是带有逗号分隔符的值列表
- r - 有没有办法改变 R 中的显着性水平(alpha)?
- css - CSS 网格结构