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

Select rows according to part of their content in pandas

I am working with a dataframe and the Pandas library and I would like to select all those rows of my payload column that its first two characters are "3c" and also those rows in which in this column its last two characters end in "3e".

I know that applying a conditional would be done in the following way,

new_df = df.loc[df['column'] == 'condition']]

And that you can search if a column contains a part of a string,

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[df[df['column']].str.contains('X', case=False)]

My question would be, how can I specify that I only want the first two characters?
Is it possible to apply a logical OR and search the first two characters for a value and the last two for another value?

I have tried things similar to the following but I don’t get what I want,

new_df= df[df['payload'][:2].str.contains('3c', case=False)]

Thank you very much!

>Solution :

Chain both conditions by Series.str.startswith and Series.str.endswith by | for bitwise OR:

new_df = df[df['payload'].str.startswith('3c') | df['payload'].str.endswith('3e')]

If need both cases:

new_df = df[df['payload'].str.startswith(('3c', '3C')) | 
            df['payload'].str.endswith(('3e', '3E'))]

Your solution is possible modify by selecting by str for first or last 2 values:

df[df['payload'].str[:2].str.contains('3c', case=False) |
   df['payload'].str[-2:].str.contains('3e', case=False)
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