Python:如何在列中只保留特定的值?
我有一个数据帧Python:如何在列中只保留特定的值?,python,string,pandas,Python,String,Pandas,我有一个数据帧df,如下所示 df: zip-code 0 00234 1 23450 2 23450 3 10786 4 0 5 xyzvd 其中类型(df['zip-code'])=str。我只想保留5位值,并删除所有剩余值 您可以对正则表达式使用str.match: z = df['zip-code'] df[z.str.len().eq(5) & z.str.isdigit()] zip-code 0 00234 1
df
,如下所示
df:
zip-code
0 00234
1 23450
2 23450
3 10786
4 0
5 xyzvd
其中
类型(df['zip-code'])=str
。我只想保留5位
值,并删除所有剩余值 您可以对正则表达式使用str.match
:
z = df['zip-code']
df[z.str.len().eq(5) & z.str.isdigit()]
zip-code
0 00234
1 23450
2 23450
3 10786
df[df['zip-code'].str.match("^\d{5}$")]
#zip-code
#0 00234
#1 23450
#2 23450
#3 10786
您可以对正则表达式使用
str.match
:
df[df['zip-code'].str.match("^\d{5}$")]
#zip-code
#0 00234
#1 23450
#2 23450
#3 10786
是,但我也想删除
xyzvd
yes之类的条目,但我也想删除xyzvd