Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use python to select first X columns and last Y columns

Tags:

python

pandas

I am trying to select column 1 to 8 and the last column from a data frame. I have some dumb way to do that

step 1: select first 8 column

df1 = df[df.columns[range(9)]]

step 2: select last column

df2 = df[df.columns[-1]]

step 3: combine step1 and step2

df1.join(df2)

is there a better way to do that in one step instead of 3 steps?

like image 751
Gavin Avatar asked Mar 06 '17 17:03

Gavin


People also ask

How do you select columns of data in Python?

Selecting columns based on their name This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. Passing a list in the brackets lets you select multiple columns at the same time.


2 Answers

Use smart column indexing:

df.iloc[:, list(range(9)) + [-1]]
like image 140
DYZ Avatar answered Nov 14 '22 23:11

DYZ


Use Concat from Pandas. This works as same as CBIND.

new_df = pd.concat([df.iloc[:,0:8],df.iloc[:,-1:]],axis = 1)
like image 26
Karmugilan JAYACHANDIRAN Avatar answered Nov 14 '22 22:11

Karmugilan JAYACHANDIRAN