I have the following dataframe:
JavaScript
x
6
1
a b x y
2
0 1 2 3 -1
3
1 2 4 6 -2
4
2 3 6 9 -3
5
3 4 8 12 -4
6
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.
Advertisement
Answer
You can rearrange columns directly by specifying their order:
JavaScript
1
2
1
df = df[['a', 'y', 'b', 'x']]
2
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.
JavaScript
1
8
1
>>> df[[c for c in df if c not in ['b', 'x']]
2
+ ['b', 'x']]
3
a y b x
4
0 1 -1 2 3
5
1 2 -2 4 6
6
2 3 -3 6 9
7
3 4 -4 8 12
8
To make it more bullet proof, you can ensure that your target columns are indeed in the dataframe:
JavaScript
1
4
1
cols_at_end = ['b', 'x']
2
df = df[[c for c in df if c not in cols_at_end]
3
+ [c for c in cols_at_end if c in df]]
4