Python.pandas: how to select rows where objects start with letters 'PL'

Viewed 15007

I have specific problem with pandas: I need to select rows in dataframe which start with specific letters. Details: I've imported my data to dataframe and selected columns that I need. I've also narrowed it down to row index I need. Now I also need to select rows in other column where objects START with letters 'pl'.

Pasted here picture of how df looks like now for better view

Is there any solution to select row only based on first two characters in it?

I was thinking about

pl = df[‘Code’] == pl*

but it won't work due to row indexing. Advise appreciated!

4 Answers

Use startswith for this:

df = df[df['Code'].str.startswith('pl')]

Fully reproducible example for those who want to try it.

import pandas as pd

df = pd.DataFrame([["plusieurs", 1], ["toi", 2], ["plutot", 3]])

df.columns = ["Code", "number"]

df = df[df.Code.str.startswith("pl")] # alternative is df = df[df["Code"].str.startswith("pl")]

The condition is just a filter, then you need to apply it to the dataframe. as filter you may use the method Series.str.startswith and do

df_pl = df[df['Code'].str.startswith('pl')]

If you use a string method on the Series that should return you a true/false result. You can then use that as a filter combined with .loc to create your data subset.

new_df = df.loc[df[‘Code’].str.startswith('pl')].copy()
Related