Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - Reverse DataFrame column order

I want to simply reverse the column order of a given DataFrame.

My DataFrame:

data = {'year': [2010, 2011, 2012, 2011, 2012, 2010, 2011, 2012],
    'team': ['Bears', 'Bears', 'Bears', 'Packers', 'Packers', 'Lions', 'Lions', 'Lions'],
    'wins': [11, 8, 10, 15, 11, 6, 10, 4],
    'losses': [5, 8, 6, 1, 5, 10, 6, 12]}
football = pd.DataFrame(data, columns=['year', 'team', 'wins', 'losses'])

Actual output:

   year     team  wins  losses
0  2010    Bears    11       5
1  2011    Bears     8       8
2  2012    Bears    10       6
3  2011  Packers    15       1
4  2012  Packers    11       5
5  2010    Lions     6      10
6  2011    Lions    10       6
7  2012    Lions     4      12

I thought this would work but it reverses the row order not column order:

football[::-1] 

I also tried:

football.columns = football.columns[::-1]

but that reversed the column labels and not the entire column itself.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A solution close to what you have already tried is to use:

>>> football[football.columns[::-1]]
   losses  wins     team  year
0       5    11    Bears  2010
1       8     8    Bears  2011
2       6    10    Bears  2012
3       1    15  Packers  2011
4       5    11  Packers  2012
5      10     6    Lions  2010
6       6    10    Lions  2011
7      12     4    Lions  2012

football.columns[::-1] reverses the order of the DataFrame's sequence of columns, and football[...] reindexes the DataFrame using this new sequence.

A more succinct way to achieve the same thing is with the iloc indexer:

football.iloc[:, ::-1]

The first : means "take all rows", the ::-1 means step backwards through the columns.

The loc indexer mentioned in @PietroBattiston's answer works in the same way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...