在 pandas 数据框中移动列 [英] move column in pandas dataframe

查看:40
本文介绍了在 pandas 数据框中移动列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数据框:

   a  b   x  y
0  1  2   3 -1
1  2  4   6 -2
2  3  6   9 -3
3  4  8  12 -4

如何移动列b和x,使它们成为数据框中的最后2列?我想按名称指定b和x,但不指定其他列.

How can I move columns b and x such that they are the last 2 columns in the dataframe? I would like to specify b and x by name, but not the other columns.

推荐答案

您可以通过指定列的顺序直接重新排列列:

You can rearrange columns directly by specifying their order:

df = df[['a', 'y', 'b', 'x']]

如果列标题是动态的较大数据框,则可以使用列表推导选择不在目标集中的每个列,然后将目标集附加到末尾.

In the case of larger dataframes where the column titles are dynamic, you can use a list comprehension to select every column not in your target set and then append the target set to the end.

>>> df[[c for c in df if c not in ['b', 'x']] 
       + ['b', 'x']]
   a  y  b   x
0  1 -1  2   3
1  2 -2  4   6
2  3 -3  6   9
3  4 -4  8  12

要使其更加安全,可以确保目标列确实在数据框中:

To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:

cols_at_end = ['b', 'x']
df = df[[c for c in df if c not in cols_at_end] 
        + [c for c in cols_at_end if c in df]]

这篇关于在 pandas 数据框中移动列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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