How to Select the Last Column of Dataframe

how to get last column of pandas series

Problem is output of GroupBy.size is Series, and Series have no columns, so is possible get last value only:

b.iloc[-1]

If use:

b.iloc[:,-1]

it return last column in Dataframe.

Here : means all rows and -1 in second position last column.

So if create DataFrame from Series:

b1 = df.groupby('a').size().reset_index(name='count')

it working like expected.

How to select all but the 3 last columns of a dataframe in Python

Select everything EXCEPT the last 3 columns, do this using iloc:

In [1639]: df
Out[1639]:
a b c d e
0 1 3 2 2 2
1 2 4 1 1 1

In [1640]: df.iloc[:,:-3]
Out[1640]:
a b
0 1 3
1 2 4

finding last column name when two columns have max value in one row python

what about taking vertical symmetry and then idxmax, i.e.,

df.iloc[:, ::-1].idxmax(axis=1)
0    x
1 z
2 z
3 z
4 y

so the df.iloc[:, ::-1] part is

   z  y  x
0 0 0 1
1 1 0 1
2 1 0 0
3 1 1 0
4 0 1 1

it's from z to x now



Another way with reindexing might be more clear in giving away the intent:

df.reindex(columns=df.columns[::-1]).idxmax(axis=1)
0    x
1 z
2 z
3 z
4 y

as above.

Read 1st column, 2nd column, and nth column to last column of panda dataframe

If you like to select columns by their numerical index, iloc is the right thing to use. You can use np.arange add a range of columns (such as between the 10th to the last one).

import pandas as pd  
import numpy as np

cols = [0, 1]
cols.extend(np.arange(10, df.shape[1]))
df.iloc[:,cols]

Alternatively, you can use numpy's r_ slicing trick:

df.iloc[:,np.r_[0:2, 10:df.shape[1]]]

Selecting first n columns and last n columns with pandas

You can use the iloc function to get the columns, and then pass in the indexes.

df.iloc[:,[0,1,-1,-2]]

How to select some specific solumns and also last column in pandas

Get last column name by indexing:

df = df[['name','age', df.columns[-1]]]


Related Topics



Leave a reply



Submit