Robert Chestnutt
Robert Chestnutt

Reputation: 322

Pandas how to select a range of columns using .filter()

Im sorry if this is way too basic, but would anyone be able to share how to select ranges of columns with Pandas' .filter() function:
Im looking to select a range of sequential columns - from 'professional' through to 'production'.
below is my effort - I also tried splitting into 2 lists

counties.\
   filter(['state', 'county', 'population', 'professional':'production']).\
   sort_values('service', ascending = False).\
   head()

Upvotes: 1

Views: 93

Answers (1)

jezrael
jezrael

Reputation: 863481

I think it filter only lists.

So here is possible select values by DataFrame.loc and join to list:

c = counties.loc[:, 'professional':'production'].columns.tolist()

df = (counties.filter(['state', 'county', 'population'] + c)
              .sort_values('service', ascending = False)
              .head())

Upvotes: 1

Related Questions