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)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章