df['Discount_rate'] = df['Discount_rate'].apply(str).apply(lambda x: float(x) if '.' in x else int(str(x)))报错invalid literal for int() with base 10: 'Discount_rate'
时间: 2024-02-01 17:02:41 浏览: 19
这个错误提示看起来是因为你的数据中存在一些异常值,导致无法转换成浮点数或整数。
你可以尝试在转换前,先查看下该列中的数据是否全部符合要求。可以使用`value_counts()`方法查看该列中的不同取值。
另外,你也可以尝试将转换函数拆分成两部分,先将字符串转换成浮点数,再用`math.isnan()`判断是否为非数字类型,如果是,则将其转换成整数。
例如:
```
import math
def convert_discount_rate(x):
x = float(x)
if math.isnan(x):
return -1
elif '.' in str(x):
return x
else:
return int(x)
df['Discount_rate'] = df['Discount_rate'].apply(str).apply(convert_discount_rate)
```
这样处理后,如果有非数字类型的数据,会被转换成-1,便于后续处理。
相关问题
df.scp_codes = df.scp_codes.apply(lambda x: ast.literal_eval(x))
这是一个将DataFrame列中的字符串转换为Python字典的操作。使用`apply`函数和`ast.literal_eval`函数来实现。`apply`函数可以对DataFrame的列进行元素级的操作,而`ast.literal_eval`函数可以将字符串转换为对应的Python字典。这行代码的作用是将`df`中名为`scp_codes`的列中的每个字符串转换为对应的字典。
df=df.apply(lambda x: x/SumRow_df, axis=0)
这行代码的作用是将DataFrame中的每一列值除以该列所有值的和,实现对每列数据进行归一化处理。其中,lambda函数定义了对每个元素进行的操作,axis=0表示沿着列方向进行操作。具体来说,SumRow_df是DataFrame中每列的和组成的Series,x表示每个元素,x/SumRow_df表示对每个元素进行除法操作。apply()函数将定义好的lambda函数应用到DataFrame的每一列上。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)