1

I've looked around but can't find an exact solution, though it should be easily accomplished task:

I have a DataFrame and I just want to move one of the columns to the front. How do I do this without having to pass the columns to a list, or is there currently no way around that?


Input:
1  2  3  4 
 C  C  C  C
 G  N  D  A
 K  M  I  L
 C  C  L  C
 G  N  D  A
 Y  F  V  H
 G  N  D  A
 G  Y  D  A

Expected output:
4  1  2  3 
C  C  C  C
A  G  N  D
L  K  M  I
C  C  C  L
A  G  N  D
H  Y  F  V
A  G  N  D
A  G  Y  D

mandosoft
  • 163
  • 1
  • 1
  • 8
  • Only problem is that it assumes the last column is the one I would want moved to the front, as it requires passing columns to a list, then reversing the list before reconstructing the dataframe. Is there a non-list oriented way to do this without assuming the last column is always the one moved to the front? – mandosoft Nov 20 '19 at 17:13

1 Answers1

1

One way could be to slicing the column index and use pd.Index.union to obtain the desired output:

df[df.columns[-1:].union(df.columns[:-1], sort=False)]

   4  1  2  3
0  C  C  C  C
1  A  G  N  D
2  L  K  M  I
3  C  C  C  L
4  A  G  N  D
5  H  Y  F  V
6  A  G  N  D
7  A  G  Y  D

Based on your comment, on order to move to the front a given column, you could do:

df[sorted(df.columns, key=lambda x: x!='4')]

   4  1  2  3
0  C  C  C  C
1  A  G  N  D
2  L  K  M  I
3  C  C  C  L
4  A  G  N  D
5  H  Y  F  V
6  A  G  N  D
7  A  G  Y  D
yatu
  • 86,083
  • 12
  • 84
  • 139