Search code examples
pythonpandaspandas-loc

pandas loc search by part of a string not using regexp


import pandas as pd


data = {'name': ['HelloWorld', 'ByeWorld'],
        'physics': [22, 33],
        'chemistry': [44, 55]}

a = pd.DataFrame(data)

b = a.loc[a['name'] == 'Hello']

print(b)

This code would not return any rows, but I would like to achieve it would return the first row, because it includes "Hello". Is there any elegant solution to solve this with the loc command?


Solution

  • You want

    b = a.loc[a['name'].str.contains('Hello')]

    also if your only looking at the start of a string you can use

    b = a.loc[a['name'].str.startswith('Hello')]

    Not

    b = a.loc[a['name'] == 'Hello']

    this line of code will only return True for a row containing ONLY Hello