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 16:05:09 浏览: 86
这个错误提示显示在 `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` 的出现。
相关问题
def comment_p(x): x = x.replace(r'+','') if '万' in x: x = x.replace(r'万','') x=float(x)*10000 return x else: return x有问题吗
根据你提供的代码,`comment_p` 函数将 `+` 符号去掉后,判断字符串中是否包含 `万` 字符。如果包含,将 `万` 字符去掉,并将字符串转换为浮点数类型,然后乘以 `10000` 得到对应的整数值。如果不包含 `万` 字符,则直接返回原字符串。
这个函数的处理方式与之前提供的代码略有不同,但在处理带有 `万` 字符的字符串时应该是可行的。不过需要注意的是,如果 `comment` 列中存在非法字符或缺失值,这个函数可能会出现错误,因此建议先进行数据清洗和预处理,确保数据的准确性和完整性。
1 def comment_p(x): ----> 2 x = x.replace('+','').replace('万','') 3 if x.isdigit(): 4 return int(x) AttributeError: 'float' object has no attribute 'replace'
根据报错信息,出现了 `AttributeError: 'float' object has no attribute 'replace'` 的错误,这是因为 `x` 可能是浮点数类型,而浮点数类型没有 `replace` 方法。可以先将浮点数类型转换为字符串类型,再进行替换操作,例如:
```
def comment_p(x):
if isinstance(x, float) and math.isnan(x):
return None
x = str(x).replace('+','').replace('万','')
if x.isdigit():
return int(x)
else:
return None
```
在这个函数中,首先判断 `x` 是否为 `NaN`,如果是,则返回 `None`。然后将 `x` 转换为字符串类型,并去掉 `+` 和 `万` 符号。最后判断字符串是否为数字,如果是,则将其转换为整数格式并返回;否则返回 `None`。
阅读全文
相关推荐

















