본문 바로가기

Python

Python - 판다스 xlsx 불러오기, 저장하기 연습문제 (infile,outfile)

'''
1. sales_2015.xlsx 파일의 january_2013 sheet의 중  "Customer Name", "Sale Amount" 컬럼만 
   sales_2015_amt.xlsx 파일로 저장하기 

2. sales_2015.xlsx 파일의 모든 sheet의 "Customer Name", "Sale Amount" 컬럼만 
sales_2015_allamt.xlsx 파일로 저장하기 
'''

# 1
import pandas as pd
infile = "sales_2015.xlsx"
outfile = "sales_2015_amt.xlsx"
df = pd.read_excel(infile,"january_2015",index_col=None)
df_value = df[["Customer Name","Sale Amount"]]
print(df_value)
writer = pd.ExcelWriter(outfile)
df_value.to_excel(writer,sheet_name="january_2013",index=False)
writer.save()
writer.close()

# 2 
import pandas as pd
infile = "sales_2015.xlsx"
outfile = "sales_2015_allamt.xlsx"
writer = pd.ExcelWriter(outfile)
df = pd.read_excel(infile,sheet_name=None,index_col=None)
row_output = []
for worksheet_name,data in df.items() :
    print("===",worksheet_name,"===")
    data_value = data[["Customer Name", "Sale Amount"]]
    data_value.to_excel(writer,sheet_name=worksheet_name,index=False)
writer.save()