Home > Enterprise >  Filtering Phone number
Filtering Phone number

Time:10-05

I am trying to filter a column that contains phone numbers in python. In that column, I want to get all phone numbers that start with 61. Could you please help me with that?

The sample data is below?

CodePudding user response:

You can use str.startswith, for example:

df[df['phone number'].str.startswith(' 61')]

CodePudding user response:

You could use str.contains with a regular expression (^[ ]61):

import pandas as pd

# test data
df = pd.DataFrame({
    "Number" : [" 61 123456789", " 1 1234567890", " 41 123456789"],
    "Country" : ["Australia", "Canada", "Switzerland"],
})

regex = "^[ ]61"

result = df[df.Number.str.contains(regex)]

print(result)
          Number    Country
0   61 123456789  Australia

Or as FionaHeJiang suggested, you should be able to use str.startswith. It works for me with my test data:

import pandas as pd

# test data
df = pd.DataFrame({
    "Number" : [" 61 123456789", " 1 1234567890", " 41 123456789"],
    "Country" : ["Australia", "Canada", "Switzerland"],
})

print(df[df["Number"].str.startswith(" 61")])
          Number    Country
0   61 123456789  Australia

If this does not work for you, you will need to provide some test data and more information so we can help you. Please always provide a Minimal Reproducible Example with your questions.

CodePudding user response:

Alternative of startswith would be using regex module You can use regex module with different types of match-making.

import re
df[re.findall(r'\ 61.*',str(df['phone number']))]
  • Related