How to select the last column of dataframe

后端 未结 7 742
北恋
北恋 2020-11-30 01:18

I have done some searching for the answer to this question, but all I can figure out is this:

df[df.columns[len(df.columns)-1]]

which to m

相关标签:
7条回答
  • 2020-11-30 02:19

    Just to add to @Anshul Singh Suryan's answer:

    When we split the dataframe to just get the last column:

    If we split like:

    y = df.iloc[:,-1:] - y remains a dataframe

    However, if we split like

    y = df.iloc[:,-1] - y becomes a Series.

    This is a notable difference that I've found in the two approaches. If you don't care about the resultant type, you can use either of the two. Otherwise you need to take care of the above findings.

    This is applicable for any number of rows you want to extract and not just the last row. For example, if you want last n number of rows of a dataframe, where n is any integer less than or equal to the number of columns present in the dataframe, then you can easily do the following:

    y = df.iloc[:,n:]
    

    Replace n by the number of columns you want. Same is true for rows as well.

    0 讨论(0)
提交回复
热议问题