Brian Brian - 28 days ago 7
Python Question

How do I reverse the column values and leave the column headers as they are

suppose I have a dataframe

df


df = pd.DataFrame([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]],
columns=['A', 'B', 'C', 'D', 'E'])


Which looks like this

A B C D E
0 1 2 3 4 5
1 6 7 8 9 10


How do I reverse the order of the column values but leave the column headers as A, B, C, D, E?

I want it to look like

A B C D E
0 5 4 3 2 1
1 10 9 8 7 6


I've tried sorting the column index
df.sort_index(1, ascending=False)
but that changes the column heads (obviously) and also, I don't know if my columns start off in a sorted way anyway.

Answer

Or you can just reverse your columns:

df.columns = reversed(df.columns)
df.sortlevel(axis=1)

#   A   B   C   D   E
#0  5   4   3   2   1
#1  10  9   8   7   6