反向DataFrame列顺序

Boo*_*d16 16 python reverse dataframe pandas

我想简单地反转给定DataFrame的列顺序.

我的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'])
Run Code Online (Sandbox Code Playgroud)

实际产量:

   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
Run Code Online (Sandbox Code Playgroud)

我认为这会工作,但它会反转行顺序而不是列顺序:

football[::-1] 
Run Code Online (Sandbox Code Playgroud)

我也尝试过:

football.columns = football.columns[::-1]
Run Code Online (Sandbox Code Playgroud)

但这颠倒了列标签,而不是整个列本身.

Ale*_*ley 30

接近您已经尝试过的解决方案是使用:

>>> 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
Run Code Online (Sandbox Code Playgroud)

football.columns[::-1]颠倒DataFrame列序列的顺序,并football[...]使用此新序列重新索引DataFrame.

一个更简洁的方法来实现同样的事情是iloc索引器:

football.iloc[:, ::-1]
Run Code Online (Sandbox Code Playgroud)

第一个:意思是"占用所有行",这::-1意味着向后逐步通过列.

loc@ PietroBattiston的答案中提到的索引器以同样的方式工作.

  • 更详细地说:“足球[反转(football.columns)]” (2认同)

Pie*_*ton 5

注意:从 Pandas v0.20 开始,.ix 索引器已被弃用,取而代之的是.iloc/ .loc

\n\n

接近EdChum 的答案......但更快:

\n\n
In [3]: %timeit football.ix[::,::-1]\n1000 loops, best of 3: 255 \xc2\xb5s per loop\n\nIn [4]: %timeit football.ix[::,football.columns[::-1]]\n1000 loops, best of 3: 491 \xc2\xb5s per loop\n
Run Code Online (Sandbox Code Playgroud)\n\n

另请注意,一个冒号是多余的:

\n\n
In [5]: all(football.ix[:,::-1] == football.ix[::,::-1])\nOut[5]: True\n
Run Code Online (Sandbox Code Playgroud)\n\n

编辑:进一步(最小)的改进是通过使用.loc而不是带来的.ix,如football.loc[:,::-1]

\n