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

Filter DataFrame using .loc and asin from an Alphanumeric List

I am trying to filter a dataframe using a list with alphanumerical values. Here is a sample dataframe below:

A B
D0102 52
Patients 150
D5175 71
DaysWorked 12

I created a list named "codes" to:

codes = ['D0102', 'D5175']

The code I used is shown below and the dataframe didn’t pull up anything:

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

new_df= df.loc[df['A'].isin(codes)]

The desired output dataframe that I want to display is this:

A B
D0102 52
D5175 71

When I changed the list named "codes" to:

codes = ['Patients', 'DaysWorked']

I used the same line of code:

new_df= df.loc[df['A'].isin(codes)]

The new dataframe pulled the correct data:

A B
Patients 150
DaysWorked 12

>Solution :

There’s a good chance that the column A of your df might have some unwanted whitespaces in it. You might wanna do this:

df.loc[df['A'].str.strip().isin(codes)]
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