본문 바로가기
  • Hello_
Python/Error

[Python_Error] TypeError: cannot concatenate object of type '<class 'dict'>'; only Series and DataFrame objs are valid

by LDwDL 2023. 2. 4.
728x90
반응형

본 포스팅은 업무 중 발생했던 오류들을 예시를 통해 어떻게 해결을 하는지 작성했다.

 

TypeError: cannot concatenate object of type '<class 
'dict'>'; only Series and DataFrame objs are valid

해당 오류는 pandas.concat을 활용할 경우 안에 인자의 리스트 요소 중 데이터프레임이 아니고 dictionary인 경우 발생한 오류이다.

 

TypeError:&nbsp;cannot&nbsp;concatenate&nbsp;object&nbsp;of&nbsp;type&nbsp;'<class&nbsp;'dict'>';&nbsp;only&nbsp;Series&nbsp;and&nbsp;DataFrame&nbsp;objs&nbsp;are&nbsp;valid

 

오류가 발생했던 코드이며, 가장 밑에 "df = pd.concat([ct_dict,xray_df])" 라인에서 오류가 나왔다.

xray_excel_path = './new_annotation.xlsx'

for i in range(10):
    ct_dict = {}

    ct_dict['name'] = 'ct_{}'.format(i+1)
    ct_dict['dcm_paths'] = './Abnormal/images/ct/{}'.format(i+1)
    ct_dict['label_paths'] = './Abnormal/labels/ct/{}'.format(i+1)
    ct_dict['dcm_extentions'] = '.dcm'
    ct_dict['label_extentions'] = '.nii.gz’

    xray_df = pd.read_excel(xray_excel_path)

    df = pd.concat([ct_dict,xray_df])

 

단순히 "xray_df"는 데이터프레임으로 선언이 되었지만, "ct_dict"는 데이터프레임이 아니라 dictionary 형태이기 때문에 발생된 것이었다. 

 

# df = pd.concat([ct_dict,xray_df])

ct_df = pd.DataFrame(ct_dict)
df = pd.concat([ct_df,xray_df])

 

다음과 같이 ct_dict을 pd.DataFrame을 활용하여 데이터프레임으로 변환시켜주면 문제는 해결되었다.

 

 

728x90
반응형

댓글