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

版权声明:欢迎分享和转载,请注明出处 shuihupo:https://blog.csdn.net/shuihupo.同时,本博客部分会在云南省高校数据化运营管理工程中心博客同步。欢迎沟通交流:[email protected] https://blog.csdn.net/shuihupo/article/details/82669552

对于一种的字符串(整数字符,加了引号),这种可以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)

猜你喜欢

转载自blog.csdn.net/shuihupo/article/details/82669552
今日推荐