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 get rows of Pandas Dataframe where the column value starts with any of given characters

I have the following Pandas Dataframe:

d = {'col1': ["aaa", "bbb", "ccc", "ddd", "acc", "bcc"]}
df = pd.DataFrame(data=d)
df

Output of the above code:

    col1
0   aaa
1   bbb
2   ccc
3   ddd
4   abb
5   bcc

I need to get the rows where the column value starts with – say – either "a" or "c". After the filtering, the result should look as the following:

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

    col1
0   aaa
1   ccc
2   abb

How can I achieve this without using a for loop?

>Solution :

Just for a and c

df = df[df["col1"].str.match('^[ac].+')]

You can include as many letters in the square brackets that you need to match on.

df = df[df["col1"].str.match('^[abcdefg].+')]
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