Search code examples
pythonpandasdata-analysis

Python - Drop rows from a Pandas DataFrame that contain numbers


I have a dataframe with one column like this:

Value
xyz123
123
abc
def

I want to remove any rows that contain numbers so I end up with a dataframe like this:

Value
abc
def

I have tried

df = df[df['Value'].str.contains(r'[^a-z]')]

but I got this error:

"TypeError: 'method' object is not subscriptable"


Solution

  • Independent from what looks like an issue with variable naming, you could be more explicit about removing only rows with numbers:

    df[~df.Value.str.contains(r'\d')]
    
      Value
    2   abc
    3   def
    

    \d:

    Matches any Unicode decimal digit (that is, any character in Unicode character category [Nd]). This includes [0-9], and also many other digit characters. If the ASCII flag is used only [0-9] is matched (but the flag affects the entire regular expression, so in such cases using an explicit [0-9] may be a better choice).