Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python str.findall返回值(如果找到一个元素)_Python_Pandas - Fatal编程技术网

Python str.findall返回值(如果找到一个元素)

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=

我想在字符串中找到一个数字,并将其作为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())
但我很确定代码不是最优的,我可以做得更短。如何执行此操作?

首先用于匹配第一个值,否则首先缺少值,然后转换为
浮点值
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