4

I have a dataframe like this

id    2013 Profits   2001 Revenues    1999 Assets...
31    xxxx           xxxx             xxxx
...

I want to drop the columns that do not start with '201' (I only want to keep the data 2010 and forward).

How can I do that?

3
  • 2
    isn't this question just the inverse of one of your previous questions stackoverflow.com/questions/45820359/…? Commented Aug 23, 2017 at 15:56
  • @EdChum you are correct, I think I'm going nuts already. Sorry about that. I wanted to make another question but I counfused everything. Do you think that I should I delete this one? Commented Aug 23, 2017 at 16:48
  • Up to you but I'm not sure how much value there is in this question, I've not close voted or down voted for that matter. Others may well feel different Commented Aug 23, 2017 at 16:51

3 Answers 3

8

Use pd.DataFrame.filter

df.filter(like='201')

   2013 Profits
id             
31         xxxx

As pointed out by @StevenLaan using like will include some columns that have the pattern string somewhere else in the columns name. We can ensure that we only get columns that begin with the pattern string by using regex instead.

df.filter(regex='^201')

   2013 Profits
id             
31         xxxx
Sign up to request clarification or add additional context in comments.

2 Comments

This also includes columns that for any other reason contain 201. use a regex to make sure that is only at the start df.filter(regex='^201')
@StevenLaan you are absolutely correct. Thanks for the reminder.
6

This will ensure that only columns starting with 201 will be kept.

df[[c for c in df.columns if c.startswith('201')]]

The same can be achieved with

df.filter(regex='^201')

Comments

4

Yet another way:

In [16]: df.loc[:, df.columns.str.contains('^201')]
Out[16]:
  2013 Profits
0         xxxx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.