0

I am using Pandas to select columns from a dataframe, olddf. Let's say the variable names are 'a', 'b','c', 'starswith1', 'startswith2', 'startswith3',...,'startswith10'.

My approach was to create a list of all variables with a common starting value.

    filter_col = [col for col in list(health) if col.startswith('startswith')]

I'd like to then select columns within that list as well as others, by name, so I don't have to type them all out. However, this doesn't work:

newdf = olddf['a','b',filter_col]

And this doesn't either:

newdf = olddf[['a','b'],filter_col]

I'm a newbie so this is probably pretty simple. Is the reason this doesn't work because I'm mixing a list improperly?

Thanks.

1 Answer 1

2

Use

newdf = olddf[['a','b']+filter_col]

since adding lists concatenates them:

In [264]: ['a', 'b'] + ['startswith1']
Out[264]: ['a', 'b', 'startswith1']

Alternatively, you could use the filter method:

newdf = olddf.filter(regex=r'^(startswith|[ab])')
Sign up to request clarification or add additional context in comments.

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.