原文链接:http://www.juzicode.com/python-example-excel-col-row-transpose
今天的例子实现对Excel表格的行列值完成转置。
原始表格为:A | B | C 1 | 2 | 3 * | ( | ) 经过转置后变为:A | 1 | *B | 2 | (C | 3 | )
方法1,用xlrd读取excel文件按照行方式存入到一个列表中,用xlwt写入文件时,按照列方式取出:
#juzicode.com/VX公众号:juzicode
import xlrd
import xlwtwb_r=xlrd.open_workbook('data_r.xls')
ws_r=wb_r.sheet_by_name('juzicode')
data_list=[]
for i in range(ws_r.nrows):data_list.append(ws_r.row_values(i))
print('data_list:',data_list)wb_w = xlwt.Workbook()
ws_w=wb_w.add_sheet('juzicode')
for i in range(ws_r.ncols):for j in range(ws_r.nrows):ws_w.write(i,j,data_list[j][i])
wb_w.save('data_w_xlwt_xlrd.xls')
方法2,用pandas读出文件生成df实例后,使用它的T属性完成转置:
#juzicode.com/VX公众号:juzicode
import pandas as pddf = pd.DataFrame(pd.read_excel('data_r.xls'))
df_t = df.T
with pd.ExcelWriter('data_w_pandas.xlsx',engine='openpyxl') as writer:df_t.to_excel(writer,header=False)
方法3,用pandas读出文件生成df实例后,使用它的transpose()方法完成转置:
#juzicode.com/VX公众号:juzicode
import pandas as pddf = pd.DataFrame(pd.read_excel('data_r.xls'))
df_t = df.transpose()
with pd.ExcelWriter('data_w_pandas2.xlsx',engine='openpyxl') as writer:df_t.to_excel(writer,header=False)