def comment_p(x): x = x.replace(r'+','') if '万' in x: x = x.replace(r'万','') x = float(x) * 10000 return int(x) else: return int(x) df['new_comment'] = df['comment'].apply(lambda x: comment_p(x)).astype('int')报错 2 def comment_p(x): ----> 3 x = x.replace(r'+','') 4 if '万' in x: 5 x = x.replace(r'万','') AttributeError: 'float' object has no attribute 'replace'
时间: 2024-01-06 21:05:09 浏览: 28
这个错误提示显示在 `comment_p` 函数中的 `x` 是一个浮点数,而浮点数类型没有 `replace` 方法,所以会出现 `AttributeError`。这可能是因为 `comment` 列中包含了一些浮点数或者其他不支持 `replace` 方法的类型。为了解决这个问题,您可以在 `comment_p` 函数中增加一些数据类型的判断和异常处理,来避免出现这样的错误。例如:
```
def comment_p(x):
if isinstance(x, str):
x = x.replace(r'+','')
if '万' in x:
x = x.replace(r'万','')
x = float(x) * 10000
return int(x)
else:
return int(x)
else:
return x
df['new_comment'] = df['comment'].apply(lambda x: comment_p(x)).astype('int')
```
这样可以确保 `comment_p` 函数中的 `x` 参数是一个字符串类型,避免了 `AttributeError` 的出现。
相关问题
代码2# 处理comment列数据 def comment_p(x): x = x.replace(r'+','') if '万' in x: x = x.replace(r'万','') x=float(x)*10000 return x else: return int(x)
根据您提供的代码,`comment_p` 函数会将带有 `+` 和 `万` 字符的字符串转换为整型或浮点数类型,并将结果返回。如果字符串中包含 `+` 字符,则将其替换为空字符串;如果包含 `万` 字符,则将其替换为空字符串并将结果乘以 `10000`。
您可以通过以下代码查看处理后的 `comment` 列的前5行数据:
```
# 处理comment列数据
def comment_p(x):
x = x.replace(r'+','')
if '万' in x:
x = x.replace(r'万','')
x = float(x) * 10000
return x
else:
return int(x)
df['new_comment'] = df['comment'].apply(lambda x: comment_p(x)).astype('int')
# 查看处理后的comment列数据的前5行
print(df['new_comment'].head())
```
这将显示处理后的 `comment` 列的前5行数据。
# 处理comment列数据 def comment_p(x): x = x.replace(r'+','') if '万' in x: x = x.replace(r'万','') x=float(x)*10000 return x else: return xdf['new_comment'] = df['comment'].apply(lambda x:comment_p(x)).astype('int')
根据您提供的代码,`comment_p` 函数中的 `return` 语句返回的是一个浮点数类型,但是 `df['new_comment']` 的数据类型被指定为整型,所以会报错。您可以将 `return` 语句中的浮点数强制转换为整型,如下所示:
```
# 处理comment列数据
def comment_p(x):
x = x.replace(r'+','')
if '万' in x:
x = x.replace(r'万','')
x = int(float(x) * 10000)
return x
else:
return int(x)
df['new_comment'] = df['comment'].apply(lambda x: comment_p(x)).astype('int')
```
这样可以确保 `df['new_comment']` 列中的数据类型是整型,避免了类型错误的出现。