프로그래밍/Python
[Python/파이썬] ValueError: invalid literal for int() with base 10: '' 에러 발생 -해결 solved
Mr.noobiest
2023. 11. 26. 00:47
발생
어떤 값을 int로 형변환 할때 ValueError: invalid literal for int() with base 10: '' 에러가 발생하였다.
import pandas as pd
data = {
'column1': ['0.001', '0.001', '0.001', '0.001'],
'column2': ['0.001', '0.001', '0.001', '0.001'],
'column3': ['0.001', '0.001', '0.001', '0.001'],
}
df = pd.DataFrame(data)
print(df)
#결과
# column1 column2 column3
# 0 0.001 0.001 0.001
# 1 0.001 0.001 0.001
# 2 0.001 0.001 0.001
# 3 0.001 0.001 0.001
df['column1'].astype(int)
#ValueError: invalid literal for int() with base 10: '0.001'
원인
소수점이 포함된 str를 int()형변환 할때 발생한다.
Python Can not change 0.xxx string to int
해결
1) float로 먼저 형변환 한뒤 int로 변경해서 소수점을 제거하면 된다.
import pandas as pd
data = {
'column1': ['0.001', '0.001', '0.001', '0.001'],
'column2': ['0.001', '0.001', '0.001', '0.001'],
'column3': ['0.001', '0.001', '0.001', '0.001'],
}
df = pd.DataFrame(data)
df['column1']=df['column1'].astype(float)
df['column1']=df['column1'].astype(int)
print(df)
# column1 column2 column3
# 0 0 0.001 0.001
# 1 0 0.001 0.001
# 2 0 0.001 0.001
# 3 0 0.001 0.001
2) apply와 split을 사용해서 . 뒤의 값들을 날려주면 된다.
import pandas as pd
data = {
'column1': ['0.001', '0.001', '0.001', '0.001'],
'column2': ['0.001', '0.001', '0.001', '0.001'],
'column3': ['0.001', '0.001', '0.001', '0.001'],
}
df = pd.DataFrame(data)
df['column1'] = df['column1'].apply(lambda x: x.split('.')[0])
print(df)
# column1 column2 column3
# 0 0 0.001 0.001
# 1 0 0.001 0.001
# 2 0 0.001 0.001
# 3 0 0.001 0.001
끝.
728x90
반응형