Skip to main content
 首页 » 编程设计

python之str.findall 返回值,如果找到一个元素

2024年11月01日8虾米姐

我想在字符串中找到一个数字并将其作为 int 返回。只有两种变体:数字不出现或只出现一次。目前我通过这段代码来做到这一点:

df['rating'] = pd.to_numeric(df['rating'].astype(str).str.findall('(\d+)').apply(lambda x: x[0] if len(x) > 0 else np.nan), errors='coerce') 
df['rating'] = pd.Series(df['rating'], dtype=pd.Int32Dtype()) 

但我很确定代码不是最优的,我可以做得更短。我该怎么做?

请您参考如下方法:

使用Series.str.extract对于匹配第一个值,否则首先缺少值,然后转换为 float,最后转换为 带 NaN 的整数:

df = pd.DataFrame({'rating':['asas','ds5dd87','sd223d']}) 
 
df['rating'] = df['rating'].astype(str).str.extract('(\d+)').astype(float).astype('Int64') 

解决方案 Series.str.findall类似,只是为了获取第一个值是使用 str[0]:

df['rating']=df['rating'].astype(str).str.findall('(\d+)').str[0].astype(float).astype('Int64') 
 
print (df) 
  rating 
0    NaN 
1      5 
2    223