sheet如下,工作表名称是'Sheet1',工作簿名称是'各地级市全要素原始数据.xlsx'。
程序如下:
import pandas as pd
import openpyxl as op
cities=['北京市','上海市','广州市','深圳市']
years=[i for i in range(2003,2019)]
file='各地级市全要素原始数据.xlsx'
ws=pd.read_excel(file)
city=list(ws['城市'])
year=list(ws['时间'])
wb=op.open(file)
ws=wb['Sheet1']
wb1=op.Workbook()
for sheet in range(8):#数字为指标个数
ws1=wb1.create_sheet(ws.cell(1,4+sheet).value)
for i in range(len(cities)):
ws1.cell(1,i+2).value=cities[i]
for i in range(len(years)):
ws1.cell(i+2,1).value=years[i]
for i in range(len(cities)):
for j in range(len(years)):
for k in range(len(city)):
if city[k]==cities[i] and year[k]==years[j]:
ws1.cell(j+2,i+2).value=ws.cell(k+2,sheet+4).value
wb1.remove_sheet(wb1['Sheet'])
wb1.save('一线城市全要素原始数据.xlsx')
运行结果: