处理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')报错1 df['new_comment'] = df['comment'].apply(lambda x:comment_p(x)).astype('int')NameError: name 'score' is not defined
时间: 2023-09-14 18:08:19 浏览: 84
根据您提供的代码,`score` 变量并没有被定义,所以会出现 `NameError`。我猜测您可能是想将 `score` 替换为 `x`,因为在 `comment_p` 函数中并没有定义 `score` 变量。您可以尝试将 `score` 替换为 `x`,如下所示:
```
# 处理comment列数据
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')
```
这样应该就可以将 `comment` 列中的数据转换为整数类型了。
相关问题
代码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']` 列中的数据类型是整型,避免了类型错误的出现。