user43953
user43953

Reputation: 109

Select multiple columns by labels in pandas not all in order

I would like to select a set of columns from a pandas dataframe, but only some of these columns are in sequential order. E.g., I would like to write something like:

df.loc[:,['a','2001':'2040']]

A similar question has been asked here, but the answers are not helpful: Select multiple columns by labels (pandas)

In my case, doing this manually is too cumbersome. Regular expressions are possible but complicated because the slice is number-oriented not text-oriented. So what is the most simple approach?

Upvotes: 2

Views: 455

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375685

You can use a list comprehension:

In [11]: df.columns
Out[11]: Index(['a', '2001', '2002', '2040', '2041'], dtype='object')

In [12]: [c for c in df.columns if c == "a" or c.isdigit() and 2001 <= int(c) <= 2040 ]
Out[12]: ['a', '2001', '2002', '2040']

In [13]: df[[c for c in df.columns if c == "a" or c.isdigit() and 2001 <= int(c) <= 2040 ]]

Upvotes: 3

Related Questions