Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 494
Brian Avatar asked Jan 17 '26 15:01

Brian


2 Answers

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
like image 72
Psidom Avatar answered Jan 20 '26 07:01

Psidom


method 1
reconstruct

pd.DataFrame(df.values[:, ::-1], df.index, df.columns)

method 2
assign values

df[:] = df.values[:, ::-1]
df

both give
enter image description here

like image 43
piRSquared Avatar answered Jan 20 '26 07:01

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!