emax
emax

Reputation: 7245

Python: how to keep only specific values in a pandas column?

I have a dataframe df like the following

df: 
    zip-code
0    00234
1    23450
2    23450
3    10786
4      0
5    xyzvd

where type(df['zip-code']) = str. I would like to keep only the 5-digit values and remove all the rest.

Upvotes: 1

Views: 967

Answers (2)

akuiper
akuiper

Reputation: 214927

You can use str.match with regex:

df[df['zip-code'].str.match("^\d{5}$")]

#zip-code
#0  00234
#1  23450
#2  23450
#3  10786

Upvotes: 5

piRSquared
piRSquared

Reputation: 294218

z = df['zip-code']
df[z.str.len().eq(5) & z.str.isdigit()]

  zip-code
0    00234
1    23450
2    23450
3    10786

Upvotes: 2

Related Questions