Reverse DataFrame Column Order

I want to just reorder the columns of this 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 changes the row order, not the column order:

 football[::-1] 

I also tried:

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

but this changed the column labels, not the entire column.

+5
source share
3 answers

A solution close to what you have already tried 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] overrides the sequence order of the DataFrame columns, and football[...] updates the DataFrame using this new sequence.

A more concise way to achieve the same thing is with the iloc index:

 football.iloc[:, ::-1] 

First : means "take all rows", ::-1 means step back through the columns.

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

+10
source

Note : Starting with Pandas v0.20, the .ix indexer is deprecated in favor of .iloc / .loc .

Next to EdChum's answer ... but faster:

 In [3]: %timeit football.ix[::,::-1] 1000 loops, best of 3: 255 µs per loop In [4]: %timeit football.ix[::,football.columns[::-1]] 1000 loops, best of 3: 491 µs per loop 

Also note that one colon is superfluous:

 In [5]: all(football.ix[:,::-1] == football.ix[::,::-1]) Out[5]: True 

EDIT: Further (minimal) improvement is achieved using .loc , not .ix , as in football.loc[:,::-1] .

+4
source

Note : Starting with Pandas v0.20, the .ix indexer is deprecated in favor of .iloc / .loc .

You can use fancy indexing .ix , pass in the columns, and then change the list to reorder:

 In [27]: football.ix[::,football.columns[::-1]] Out[27]: 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 

<strong> timings

 In [32]: %timeit football[football.columns[::-1]] 1000 loops, best of 3: 421 µs per loop In [33]: %timeit football.ix[::,football.columns[::-1]] 1000 loops, best of 3: 403 µs per loop 

Unusual indexing in this case is a little faster

+1
source

Source: https://habr.com/ru/post/1210545/


All Articles