Khaine775
Khaine775

Reputation: 2765

Pandas selecting certain columns and n last columns in a DataFrame

I have a DataFrame with a number of columns. I want to select some specific columns from this DataFrame which are scattered throughout, and then I want the last n columns after filtering on these specific columns.

X = dataset.ix[['Dollars', 'Rate', 'Hours', 'BUY', 'SELL'],:]

These are the specific columns I want:

'Dollars', 'Rate', 'Hours', 'BUY', 'SELL'

And then I just want the rest of the columns in the DataFrame immediately after selecting the last of 5 columns, hence the ,:. Example:

Given columns BUY | some unwanted column | SELL | ... | ..., I want to select all the columns coming right after the SELL column.

I do get all of them selected using this method, but they're all NaN.

What am I doing wrong?

Upvotes: 1

Views: 521

Answers (1)

cs95
cs95

Reputation: 402493

Do a little list manipulation with your columns:

c = ['Dollars', 'Rate', 'Hours', 'BUY', 'SELL']
i = df.columns.get_loc(c[-1]) + 1

c += df.columns[i:].tolist()    

df[c]

Also, note that ix is deprecated in favour of loc/iloc based indexers, so please refrain from using it.

Upvotes: 2

Related Questions