Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a copy of dataframe while using filter like and specifying one static column

I have a table that looks like so

Class Health (R) Pension (R) Health (E) Pension (E)
10 1.00 2.50 1.25 3.00
11 1.00 2.50 1.25 3.00
12 1.00 2.50 1.25 3.00

The rows with (E) and (R) are created dynamically with a pandas pivot function. That means I won’t always know the name of the columns to directly specify it in a typical function like this:

df = df['column', 'column', 'column']
df.filter(like = "(R)") 

The filter function above works fantastic but, the only issue is that I have to also bring in the class column from the table.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried using.

df.filter(regex = r"(Class|(R)") 

This one gives me the Class but will also for some reason pull any of the columns that have () in them.

What is the best way to extract the class and the columns with (R) to create a new dataframe?

Thank you in advance!

>Solution :

You need to escape your parentheses, and you don’t need any on the outside:

df.filter(regex=r'Class|\(R\)')

Or without a regex:

df[df.columns[df.columns.str.contains('(R)')].union(['Class'])]

Output:

  Class Health (R) Pension (R)
0   ...        ...         ...
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading