Anupam Kumar
Anupam Kumar

Reputation: 173

Selecting columns in Pandas dataframe based on Condition

I have an Excel sheet where columns are like this:

![Day 1

Now the next day it can change like this

Day 2

So every time I have to select Name column and then after Class and just before Porting. So in between one day it can have 2 column and another day it can have 4 column.

Any idea how to achieve this.

Upvotes: 0

Views: 336

Answers (2)

Vit
Vit

Reputation: 111

column_to_select = ['Name','Age','Sim','Salary','Address'] ## make a variable list of columns to be selected ##

df = pd.DataFrame(data, columns_to_select)## while reading data pass the column list to select ##

Upvotes: 0

jezrael
jezrael

Reputation: 862441

If need select all columns between Class and Porting include this columns:

df.loc[:, 'Class':'Porting']

If need exclude columns Class and Porting:

df.iloc[:, df.columns.get_loc('Class')+1:df.columns.get_loc('Porting')]

For include first column you can use this solution:

df.iloc[:, np.r_[0, df.columns.get_loc('Class')+1:df.columns.get_loc('Porting')]]

Upvotes: 2

Related Questions