본문 바로가기

프로그래밍/Python

파이썬으로 여러 엑셀 파일 필터링 후 한 파일로 합치기

한 폴더에 포함된 여러 데이터 파일을 한 번에 필터링하고 파일 하나로 합치고 싶을 때 사용하는 자동화 코드입니다.

 

import os
import pandas as pd

path = 'C:/상권분석/유동인구/'
#파일 경로명 변경
file_list = os.listdir(path)
file_list_py = [file for file in file_list if file.endswith('.csv')]
excel = pd.DataFrame()

for i in file_list_py:
    df = pd.read_csv(path+i,encoding='euc-kr')
    df = df[df['행정동'] =='충장동'] #필터링
    excel = excel.append(df,ignore_index=True) #파일 하나에 다른 파일 추가하기(파일 합치기)

excel.to_csv(path+'충장로_개폐업.csv',index=False,encoding='euc-kr')
#파일 저장하기

path에 사용하고 싶은 폴더의 경로로 변경하시면 됩니다. 

file_list_py = [file for file in file_list if file.endswith('.csv')]

.csv로 끝나는 파일들을 사용합니다.

폴더 안의 하위 파일들이 csv가 아닌 excel 파일이라면 .excel으로 변경하시면 됩니다.

 

print(excel.head()) 와 print(excel.tail())을 확인하여 처음과 끝 부분의 행을 5개씩 확인할 수 있습니다.

가지고 계신 파일과 비교하여 자동화가 잘 이루어졌는지 확인하면 되겠습니다.

 

 

# 한 파일에 계속 추가하는 코드 
import os
import pandas as pd

path = 'C:/상권분석/상권_CSV/'
file_list = os.listdir(path)
file_list_py = [file for file in file_list if file.endswith('.csv')]
excel = pd.DataFrame()

for i in file_list_py:
    data = pd.read_csv(path+i,encoding='cp949')
    
    #필터링 내용 변경
    data = data[data['소재지전체주소'].astype(str).str.contains('충장로',na=False)] 
    #string으로 변환 후 충장로가 포함된 행만 추출
    data['폐업일자'].fillna(0,inplace = True)
    
    #날짜형으로 변환
    data['폐업일자']=data['폐업일자'].astype('int')
    data['폐업일자']=data['폐업일자'].astype('str')
    data['폐업일자'] = pd.to_datetime(data['폐업일자'], infer_datetime_format=True,errors='coerce')
    data = data[(data['폐업일자']>='2017-01-01') | (data['폐업일자'].isnull())]
    
    excel = excel.append(data,ignore_index=True)

excel.to_csv(path+'충장로.csv',index=False,encoding='euc-kr')

 

다음은 폐업일자가 2017년 이후이며 폐업일자가 null인(영업중인) 행만 추출하여 통합하는 방법입니다. 

csv파일에서 날짜가 20170501 형식으로 저장되어있어 날짜 형식으로 변환하였습니다. 

제가 사용한 파일은 float 타입으로 형성되어 바로 string으로 변환시 소수점이 생겨 int로 변환 후 string으로 변환하였습니다. 

 

 

 

 

필터링 내용을 변경하고 싶다면 빨간 색으로 그린 부분만 바꾸면 됩니다.

먼저 한 파일을 대상으로 필터링 코드를 짠 뒤에 잘 돌아가는 것을 확인한 뒤에 전체 파일에 적용하는 밑의 코드에 추가해주시면 되겠습니다.