startswith() function in pandas – column starts with specific string in python dataframe

In this tutorial we will use startswith() function in pandas, to test whether the column starts with the specific string in python pandas dataframe. lets see an example of startswith() Function in pandas python

Create dataframe:

## create dataframe

import pandas as pd
d = {'Quarters' : ['quarter1','quarter2','quarter3','quarter4'],
     'Description' : ['First Quarter of the year', 'Second Quarter of the year', 'Third  Quarter of the year', 'Fourth Quarter of the year'],
     'Revenue':[23400344.567,54363744.678,56789117.456,4132454.987]}
df=pd.DataFrame(d)
print df	

resultant dataframe will be

column starts with specific string in python dataframe 1

Now let’s check whether the description column in the above dataframe starts with the String “First”.

#startswith function in python to check if the column starts with string "First" 

df['starts_with'] = map(lambda x: x.startswith('First'), df['Description'])
print df

If the string starts with First then it returns True. If not it returns False. So the resultant dataframe will be

column starts with specific string in python dataframe 2

previous column starts with specific string in python dataframe startswith() function in pandas                                                                                                           next column starts with specific string in python dataframe pandas startswith() function in pandas

Author

  • Sridhar Venkatachalam

    With close to 10 years on Experience in data science and machine learning Have extensively worked on programming languages like R, Python (Pandas), SAS, Pyspark.