如何交换两个DataFrame列? [英] How to swap two DataFrame columns?

查看:1138
本文介绍了如何交换两个DataFrame列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MATLAB中,要交换表A的第一和第二列,可以这样做 1

In MATLAB, to swap the first and second columns of a table A, one would do this1

A = A(:, [2 1 3:end]);

如果A是大熊猫DataFrame,还有类似的便捷方法吗?

Is there a similarly convenient way to do this if A were a pandas DataFrame instead?

1 MATLAB使用基于1的索引.

1 MATLAB uses 1-based indexing.

推荐答案

pandas具有执行此操作的reindex方法.您只需要按所需顺序提供一个列名列表:

pandas has reindex method that does it. You just need to give a list with the column names in the order you wish:

columns_titles = ["B","A"]
df=df.reindex(columns=columns_titles)

欢呼

这篇关于如何交换两个DataFrame列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆