如何获得仅包含字母数字值的值?



我有两列对象数据类型,如

col1             col2  
AB               AB123
BC123            SG
BG274            HF
DC               DG789
DG156            HD

我希望我的输出像

output
                             BC123
BG274
DG789
DG156

我已经尝试了rg表达式,我得到我的col1作为我的输出

如果我理解正确,您可以屏蔽数据和fillna:

m1 = df['col1'].str.fullmatch(r'[a-zA-Z]+d+')
m2 = df['col2'].str.fullmatch(r'[a-zA-Z]+d+')
(df['col1'].where(m1)
.fillna(df['col2'].where(m2))
)

用于任意列数的泛型方法:

cols = ['col1', 'col2']
df[cols].where(
df[cols]
.apply(lambda s: s.str.fullmatch(r'[a-zA-Z]+d+'))
).bfill(axis=1).iloc[:, 0]

输出:

0    AB123
1    BC123
2    BG274
3    DG789
4    DG156
Name: col1, dtype: object

可以使用regx进行过滤

def regex_filter(val, rex):
if val:
mo = re.search(rex, val)
if mo:
return True
else:
return False
else:
return False
df[df['col1'].apply(lambda x : regex_filter(x,"[A-Z]+[0-9]+"))]['col1']
Out[103]: 
1    BC123
2    BG274
4    DG156

您可以在数据库查询中这样做:

(For SQL Server)

从col1

中选择字母数字值
select col1 from table1 where col1 like  '%[A-Za-z]%' and col1 like '%[0-9]%'

从col1和col2中选择唯一的字母数字值

create table table1(col1 varchar(50), col2 varchar(50));
insert into table1 values('AB','AB123');
insert into table1 values('BC123','SG');
insert into table1 values('BG274','1');
insert into table1 values('DC','DG789');
insert into table1 values('DG156','HD');

查询:

select col1 from table1 where col1 like  '%[A-Za-z]%' and col1 like '%[0-9]%'
union
select col2 from table1 where col2 like  '%[A-Za-z]%' and col2 like '%[0-9]%'

输出:

<表类>col1tbody><<tr>AB123BC123BG274DG156DG789

最新更新