1

I would like to see some columns in a dataframe but from the tail of columns. Not rows.

Usually when you want to check the dataframe the following will be the easiest way to do.

print(df.head(5))

             Au        Ag        Al        As  ...        Zn        Zr  SAMPLE    Alt
    0 -0.657577 -1.154902 -0.638272  1.541579  ...  0.477121  0.462398   GH101    phy
    1 -2.431798  0.149219 -0.537602  1.086360  ...  1.681241 -0.301030   GH102  ad-ag
    2 -2.568636  0.178977 -0.346787  1.025306  ...  1.681241 -0.154902   GH103  ad-ag
    3 -2.455932  0.722634 -0.568636  1.378398  ...  1.113943 -0.301030   GH104  ad-ag
    4 -3.698970 -1.522879 -0.292430  1.045323  ...  1.556303 -0.154902   GH105    phy

However, I would like to check the columns on the right side of this print result (from "Alt" to leftwards), and check 5 columns for example.

Is there anyway to do so?

Tim
  • 161
  • 9
  • Maybe `df[df.columns[-5:]]`? – ernest_k May 08 '19 at 05:20
  • Sorry for the duplication. It seems the way I searched wasn't good enough. Also I didn't realize I can use iloc for selecting columns backwards. Thank you for letting me know. – Tim May 08 '19 at 05:28

2 Answers2

4

You can use iloc for this, which allows integer-based indexing of a DataFrame. It takes the syntax [i, j], where i indexes rows and j indexes columns, and allows slicing. (docs here)

In this case, you want all the rows and the last five columns, so you can do this:

df.iloc[:, -5:]
gmds
  • 19,325
  • 4
  • 32
  • 58
1

You can do:

df[df.columns[-5:]]

or:

df.T.iloc[-5:]

To select the last five elements (columns).

For rows you can do:

df.iloc[-5:]
R4444
  • 2,016
  • 2
  • 19
  • 30
  • 2
    That is the equivalent of `df.tail(5)`, and selects the last 5 *rows*. OP wants the last 5 *columns*. – gmds May 08 '19 at 05:21