Reverse DataFrame column order

三世轮回 提交于 2019-11-30 08:26:38

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.

Pietro Battiston

Note: As of Pandas v0.20, .ix indexer is deprecated in favour of .iloc / .loc.

Close 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 notice one colon is redundant:

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

EDIT: a further (minimal) improvement is brought by using .loc rather than .ix, as in football.loc[:,::-1].

EdChum

Note: As of Pandas v0.20, .ix indexer is deprecated in favour of .iloc / .loc.

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

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

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

fancy indexing is marginally faster in this case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!