Ariful Haque
Ariful Haque

Reputation: 163

Filtering out string values in Python Pandas Dataframe

I am using Python Pandas.

For example, I have a dataframe as follows

index, name, acct_no, city
1, alex, 10011, huntington
2, rider, 100AB, charleston
3, daniel, A1009, bonn
4, rice, AAAA1, new york
5, ricardo, 12121, london

From this dataset, I would like to get ONLY those records who donot have any string in the acct_no column.

So, I would like to get the following result from the above dataset. In the following result, there is no string in the values of the acct_no column.

index, name, acct_no, city
1, alex, 10011, huntington
5, ricardo, 12121, london

Which code will give me such result?

Upvotes: 0

Views: 53

Answers (2)

rje
rje

Reputation: 6418

Another solution might be to use pd.to_numeric, which tries to convert a value to a number. When it fails we can let it return nan (by specifying errors='coerce'), and then we drop all nan values:

df.acct_no = pd.to_numeric(df.acct_no, errors='coerce')
df.dropna()

Upvotes: 0

BENY
BENY

Reputation: 323226

May check str.contains

df1=df[~df.acct_no.str.contains('[a-zA-Z]')]
df1
Out[119]: 
   index      name acct_no         city
0      1      alex   10011   huntington
4      5   ricardo   12121       london

Or using to_numeric and filter by notna

df[pd.to_numeric(df.acct_no,errors='coerce').notna()]

Upvotes: 2

Related Questions