Search code examples
pythonpandasdataframeseries

How to check if a pandas dataframe contains only numeric values column-wise?


I want to check every column in a dataframe whether it contains only numeric data. Specifically, my query is not about the datatype, but instead, I want to check every value in each column of the dataframe whether it's a numeric value.

How can I find this out?


Solution

  • You can check that using to_numeric and coercing errors:

    pd.to_numeric(df['column'], errors='coerce').notnull().all()
    

    For all columns, you can iterate through columns or just use apply

    df.apply(lambda s: pd.to_numeric(s, errors='coerce').notnull().all())
    

    E.g.

    df = pd.DataFrame({'col' : [1,2, 10, np.nan, 'a'], 
                       'col2': ['a', 10, 30, 40 ,50],
                       'col3': [1,2,3,4,5.0]})
    

    Outputs

    col     False
    col2    False
    col3     True
    dtype: bool