Python小点dian儿: ValueError: invalid literal for int() with base 10

对于一种的字符串(整数字符,加了引号),这种可以int(“num”)即可达到效果,

同理int类型的数据,str(num),就可以实现 "num"的类型转换:

>>> int("3")
3
>>> str(3)
'3'
>>> int(1.23)
1
>>> int("3")
3
>>> str(1.23)
'1.23'
>>> str(3)
'3'

>>> "1.23".astype(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'astype'

那我们的数据是“num.num”这种形式呢?

我对数据中的“1.23”此种类型的数据需要舍去小数点,取整,但是Int(“1.23”)是不可以得到1的,具体报错如下:

>>> int("1.23")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.23'
>>> "1.23".astype(int)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'astype'

对于这种转换,"float"字符串转换为int,目前折中的方法就是  int(float("float_str")),即引入一个中转变量:中转一下c=float(a) b=int(c)

或者:

print(df[each].dtype)
df[each] = df[each].astype(float)
df[each] = df[each].astype(int)
print(df[each].dtype)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值