Python ProgrammingPython Programming

How to filter rows containing a string pattern in Pandas DataFrame?

Filter rows which contain specific keyword:

import pandas as pd

df = pd.DataFrame({'DateOfBirth': ['1986-11-11', '1999-05-12', '1976-01-01',
                                   '1986-06-01', '1983-06-04', '1990-03-07',
                                   '1999-07-09'],
                   'State': ['NY', 'TX', 'FL', 'AL', 'AK', 'TX', 'TX']
                   },
                  index=['Jane', 'Nick', 'Aaron', 'Penelope', 'Dean',
                         'Christina', 'Cornelia'])
print(df)

print("\n---- Filter with State contains TX ----\n")
df1 = df[df['State'].str.contains("TX")]

print(df1)


C:\pandas>pep8 example43.py
 
C:\pandas>python example43.py
          DateOfBirth State
Jane       1986-11-11    NY
Nick       1999-05-12    TX
Aaron      1976-01-01    FL
Penelope   1986-06-01    AL
Dean       1983-06-04    AK
Christina  1990-03-07    TX
Cornelia   1999-07-09    TX
 
---- Filter with State contains TX ----
 
          DateOfBirth State
Nick       1999-05-12    TX
Christina  1990-03-07    TX
Cornelia   1999-07-09    TX
 
C:\pandas>