본 포스팅에서는 "pandas.concat을 활용하여 데이터 프레임을 합치는 방법"과 "for문을 활용하여 엑셀 데이터를 위로 혹은 밑으로 계속 붙이는 방법"에 대해 설명하고자 한다.
Dataframe 합치기
다음과 같이 두 가지 엑셀 파일이 있고 이 두 개를 각각 데이터프레임으로 로드하여 합쳐보자.
csv 파일 혹은 xlsx 파일을 읽고 데이터프레임을 사용하는 방법은 아래 링크를 참고하면 된다.
우선 각각의 엑셀 파일을 로드시키자.
import pandas as pd
excel_path = './annotation.xlsx'
xray_excel_path = './new_annotation.xlsx'
df = pd.read_excel(excel_path)
new_df = pd.read_excel(xray_excel_path)
이 두 개의 데이터프레임을 합치기 위해서는 "pd.concat([데이터프레임_1, 데이터프레임_2])"를 활용하면 된다.
combined_df = pd.concat([df,new_df])
combined_df
for 문으로 엑셀 데이터 위로 붙이기
우선 이를 진행하기 위해서는 for loop문 안에 3가지 step이 필요하다.
1. pd.read_excel : 엑셀 파일 읽기
2. pd.concat : 데이터 프레임 concat
3. df.to_excel : 엑셀 파일 저장
# for 문으로 엑셀 데이터 밑으로 붙이기 코드
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([pd.DataFrame(ct_dict),xray_df]) # 새로운 데이터 위로
df.to_excel('./new_annotation.xlsx',index=False,index_label=False)
예시 코드는 new_annotation.xlsx파일을 읽어 안에 내용들 위로 순서대로 내용이 추가되는 알고리즘이다.
우선 for 문 안에서 엑셀 데이터 위에 붙일 내용을 dictionary 형태로 선언한다.
그리고 타겟이 되는 엑셀 파일을 pd.read_excel로 읽어준다. 로드된 데이터프레임과 새롭게 선언된 dicionary 형태의 데이터를 pd.concat 하기 위해 pd.DataFrame으로 형식을 통일시켜 준 뒤 합쳐준다.
이때 기존 데이터프레임 위로 내용이 추가가 되어야 하기 때문에 "pd.concat(["추가될 데이터","기존 데이터"])" 순으로 입력해야 한다.
마지막으로 합쳐진 데이터프레임을 같은 경로와 파일명으로 df.to_excel을 사용하여 덮어쓰기를 한다.
위 과정들을 for loop을 통해 반복시키면 아래 그림과 같이 계속적으로 데이터들이 순서대로 위로 붙여지게 된다.
for 문으로 엑셀 데이터 밑으로 붙이기
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([xray_df, pd.DataFrame(ct_dict)]) # 새로운 데이터 밑으로
df.to_excel('./new_annotation.xlsx',index=False,index_label=False)
코드 알고리즘은 모두 동일하다. 다만 새로운 데이터프레임을 기존 데이터프레임 밑으로 위치시켜야 하기 때문에 "pd.concat(["기존 데이터","추가될 데이터"])" 순으로 입력시키면 밑으로 데이터가 자동으로 축적될 것이다.
'Python > Pandas' 카테고리의 다른 글
[Python] Pandas를 활용하여 xls 파일 읽기 (0) | 2023.02.09 |
---|---|
[Python] Pandas로 암호화된 엑셀 파일 읽기 (0) | 2023.02.09 |
[Python] pandas로 xlsx 파일과 csv 파일 읽기 (0) | 2023.02.02 |
[Python] pandas로 엑셀 읽고 저장하기 (0) | 2023.01.31 |
댓글