Python str.findall返回值(如果找到一个元素)
我想在字符串中找到一个数字,并将其作为int返回。只有两种变体:数字不出现或只出现一次。目前,我通过以下代码执行此操作:Python str.findall返回值(如果找到一个元素),python,pandas,Python,Pandas,我想在字符串中找到一个数字,并将其作为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=
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())
但我很确定代码不是最优的,我可以做得更短。如何执行此操作?首先用于匹配第一个值,否则首先缺少值,然后转换为浮点值
s,最后转换为带有NaN的整数:
df = pd.DataFrame({'rating':['asas','ds5dd87','sd223d']})
df['rating'] = df['rating'].astype(str).str.extract('(\d+)').astype(float).astype('Int64')
与的解决方案类似,仅获取第一个值时使用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