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

Raja Sahe S picture Raja Sahe S · Jan 29, 2019 · Viewed 21.7k times · Source

I want to check every column in a dataframe whether it contains only numeric. How can i find it.

Answer

rafaelc picture rafaelc · Jan 29, 2019

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