반응형
안녕하세요 :) !
이번에는 Python에서 Pandas로 excel 생성 및 쓰는 법에 대해 알아보겠습니다.
우선 패키지 설치를 해야합니다.
pip install pandas
No module named 'openpyxl' 뜰때에는
pip install openpyxl
설치를 해줍니다.
이제 excel 만드는 것부터 시작하겠습니다.
1. 기본 액셀만들기
import pandas as pd
table = pd.DataFrame(
{
'name' : ['Kim','Lee','Oh','Lim','Choe'],
'age' : ['26','17','23','22','15'],
'성별' : ['M','W','M','M','W']
}
)
table.to_excel('./practice.xlsx')
pd.DataFrame으로 Excel 형식을 만들수 있습니다. 공식같은거니까 익숙해지면 편해집니다 :) (까먹으면 검색ㅎ)
그 결과로
이렇게 나옵니다.
2. Index 없애고 액셀만들기
아까 결과에서 나온 A열에 있는 숫자를 Index라고 부르고, 'name', 'age' ,'성별' 은 column 이라고 부릅니다.
Index를 없애서 좀더 깔끔하게 만들 수 있습니다.
import pandas as pd
table = pd.DataFrame(
{
'name' : ['Kim','Lee','Oh','Lim','Choe'],
'age' : [24,17,23,22,15],
'성별' : ['M','W','M','M','W']
}
)
print(table)
table.to_excel('./practice.xlsx',index=False)
왼쪽에 Index 숫자가 사라지고 깔끔해졌습니다.
3. sheet 이름 변경하기
기본적으로 sheet1 이라고 저장되는데 sheet1의 이름도 변경해봅시다.
import pandas as pd
table = pd.DataFrame(
{
'name' : ['Kim','Lee','Oh','Lim','Choe'],
'age' : [24,17,23,22,15],
'성별' : ['M','W','M','M','W']
}
)
print(table)
table.to_excel('./practice.xlsx',index=False, sheet_name='practice')
sheet_name만 추가해주면 변경이가능합니다
4. sheet 여러개 사용하기
table2를 하나더 만들어서 sheet를 두개 저장해보겠습니다.
import pandas as pd
table = pd.DataFrame(
{
'name' : ['Kim','Lee','Oh','Lim','Choe'],
'age' : [24,17,23,22,15],
'성별' : ['M','W','M','M','W']
}
)
table2 = pd.DataFrame(
{
'name' : ['BoYe','Ju','Sung','Chae','Jung'],
}
)
with pd.ExcelWriter('/home/tukim/Wrokspace/practice.xlsx') as writer:
table.to_excel(writer,index=False, sheet_name='practice')
table2.to_excel(writer,index=False, sheet_name='practice2')
with as 구문이 쓰였는데
with pd.ExcelWriter(파일 경로) as 파일 객체 - > 한꺼번에 저장이 가능하게 됩니다.
table2에 있는 DataFrame와 practice2라는 sheet가 만들어졌습니다 :)
반응형
댓글