1
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13] ['Adam', 14]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)

    Name    Age
0   Alex    10
1   Bob     12
2   Clarke  13
3   Adam    14

I want to get only Names starting with A . I tried following code mask = df['Name'].str.contains("A*")

 mask
 0    True
 1    True
 2    True
 Name: Name, dtype: bool 

 df = df[mask]

   Name    Age

0    Alex    10
1   Bob      12
2   Clarke   13

but I want to get the result as Name Age

0    Alex    10
1
  • Missing a comma in your data: data = [['Alex',10],['Bob',12],['Clarke',13], ['Adam', 14]] Commented Sep 17, 2024 at 23:53

2 Answers 2

4

Use this:

mask = df['Name'].str.startswith("A")

For example:

In [52]: df
Out[52]: 
     Name  Age
0    Alex   10
1     Bob   12
2  Clarke   13
3    Adam   14

In [53]: mask = df['Name'].str.startswith("A")

In [54]: df[mask]
Out[54]: 
   Name  Age
0  Alex   10
3  Adam   14

For regular expression matching, as suggested by @swiftg:

mask = df['Name'].str.match("^A.*")
Sign up to request clarification or add additional context in comments.

4 Comments

Also, I want to check for regular expressions like A, * , how to handle such cases
mask = df['Name'].str.match("^A.*") for regular expression matching.
@TECHI, * matching is "glob" matching, different from regex. Please look it up.
how to handle only * is input then?
0

Your question asks about using a regular expression (see comment by swftg in first, non-regexp answer). On string columns, Pandas provides the match() method to use matching with regular expressions.

So, for the example you give above, if you want to find all names that start with "A", you would need a mask like:

mask = df['Name'].str.match('^A.*')

If I examine df[mask] I get:

    Name    Age
0   Alex    10
3   Adam    14

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.