Selecting last n columns and excluding last n columns in dataframe

前端 未结 3 501
深忆病人
深忆病人 2020-12-05 14:01

How do I:

  1. Select last 3 columns in a dataframe and create a new dataframe?

I tried:

y = dataframe.iloc[:,-3:]
3条回答
  •  盖世英雄少女心
    2020-12-05 14:44

    This is because of using integer indices (ix selects those by label over -3 rather than position, and this is by design: see integer indexing in pandas "gotchas"*).

    *In newer versions of pandas prefer loc or iloc to remove the ambiguity of ix as position or label:

    df.iloc[-3:] see the docs.

    As Wes points out, in this specific case you should just use tail!

    It should also be noted that in Pandas pre-0.14 iloc will raise an IndexError on an out-of-bounds access, while .head() and .tail() will not:

    pd.version '0.12.0' df = pd.DataFrame([{"a": 1}, {"a": 2}]) df.iloc[-5:] ... IndexError: out-of-bounds on slice (end) df.tail(5) a 0 1 1 2 Old answer (depreciated method):

    You can use the irows DataFrame method to overcome this ambiguity:

    In [11]: df1.irow(slice(-3, None)) Out[11]: STK_ID RPT_Date TClose sales discount 8 568 20080331 38.75 12.668 NaN 9 568 20080630 30.09 21.102 NaN 10 568 20080930 26.00 30.769 NaN Note: Series has a similar iget method.

提交回复
热议问题