I have a dataframe. I want to check if a particular column has numeric values or not using regex matching. When I use str.contains
it shows an error like below. What is the correct way to check if all the values in a column have numeric values or not?
JavaScript
x
11
11
1
df=
2
Roll.No Words
3
20 two
4
30 three
5
40 four
6
50 five
7
60 Nan
8
70 Nan
9
df = df[df['Roll.No'].str.contains(r'[^0-9]', na=True)]
10
Error: AttributeError: Can only use .str accessor with string values!
11
Advertisement
Answer
You can use
JavaScript
1
2
1
df = df[df['Roll.No'].astype(str).str.contains(r'[^0-9]', na=True)]
2
With .astype(str)
, you will be able to run a regex on the numeric column.
The .str.contains(r'[^0-9]', na=True)
expression will find all values that contain at least one char that is not a digit (like dots or commas).