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 on a pandas string column as numeric without creating a new column

This is a quite easy task, however, I am stuck here. I have a dataframe and there is a column with type string, so characters in it:

Category
AB00
CD01
EF02
GH03
RF04

Now I want to treat these values as numeric and filter on and create a subset dataframe. However, I do not want to change the dataframe in any way. I tried:

df_subset=df[df['Category'].str[2:4]<=3]

of course this does not work, as the first part is a string and cannot be evaluated as numeric and compared to 69.

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 tried

df_subset=df[int(df['Category'].str[2:4])<=3]

but I am not sure about this, I think it is wrong or not the way it should be done.

>Solution :

Add type conversion to your expression:

df[df['Category'].str[2:].astype(int) <= 3]

  Category
0     AB00
1     CD01
2     EF02
3     GH03
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