언빌리버블티

[Python] AttributeError: 'str' or 'list' object has no attribute 'astype' (dataframe str.split().astype() 에러) 본문

Language/ErrorNote

[Python] AttributeError: 'str' or 'list' object has no attribute 'astype' (dataframe str.split().astype() 에러)

나는 정은 2022. 10. 12. 11:07

AttributeError: 'str' or 'list' object has no attribute 'astype'

다음 데이터에서 기간의 연도를 split을 통해 나누고 , int 형식으로 바꾼 뒤 새로운 파생 변수를 만들고자 하였다.

split()으로 반환한 결과값에 대해 astype() 메서드가 적용되지 않고 에러가 나서 그 이유와 해결 방법을 알아보았다. 

 


df. astype()

  • df.astype의 경우 데이터 프레임의 데이터 타입을 바꾸는 함수이다.
    • 따라서 리스트와 문자열을 반환하는 split에 바로 적용해주게 되면 error가 발생한다.
df_first_melt['기간'].str.split('년')[0].astype(int)
AttributeError: 'list' object has no attribute 'astype'
df_first_melt['기간'].str.split('년')[0][0].astype(int)
AttributeError: 'str' object has no attribute 'astype'

 

df.str.split( expand = True )

str.split() 반환값의 형식 변경 

  • split() 결과값이 list가 담긴 seires를 반환하기 때문에 데이터프레임으로 반환하는 옵션인 expand를 True로 지정한다.
df_first_melt['기간'].str.split('년',expand = True)[0].astype(int)
0      2013
1      2013
2      2013
3      2013
4      2013
       ... 
352    2015
353    2015
354    2015
355    2015
356    2015
Name: 0, Length: 357, dtype: int32

String Accessor를 사용한 데이터 값 나누기

str.split( expand = True )

  • expand 옵션을 지정하면 데이터를 split한 결과를 데이터프레임 형식으로 확장한다.
    • 모든 열 값에 대해 데이터를 처리하고 싶을 때 (.astype() 적용 등등) expand를 지정해주면 된다.

 

Comments