Home > database >  Filter DataFrame using .loc and asin from an Alphanumeric List
Filter DataFrame using .loc and asin from an Alphanumeric List

Time:03-26

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:

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

CodePudding user response:

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)]
  • Related