Excel文件檢查 from xlrd import open_workbookinput_file='sales_2013.xlsx'workbook=open_workbook(input_file)print('Number of worksheets',workbook.nsheets)for worksheet in workbook.sheets(): print('sheet name:',worksheet.name,'\trows:',worksheet.nrows,'\tcolumns:',worksheet.ncols)
讀寫Excel文件
格式化Excel文件中的數(shù)據(jù) from datetime import datefrom xlrd import open_workbook,xldate_as_tuplefrom xlwt import Workbookinput_file='sales_2013.xlsx'output_file='date_format.xls'output_workbook=Workbook()output_worksheet=output_workbook.add_sheet('jan_2013_output')with open_workbook(input_file) as workbook: worksheet=workbook.sheet_by_name('january_2013') for row_index in range(worksheet.nrows): row_list_output=[] for col_index in range(worksheet.ncols): if worksheet.cell_type(row_index,col_index) ==3: date_cell=xldate_as_tuple(worksheet.cell_value(row_index,col_index),workbook.datemode) date_cell=date(*date_cell[0:3]).strftime('%m%d%Y') row_list_output.append(date_cell) output_worksheet.write(row_index,col_index,date_cell) else: non_date_cell=worksheet.cell_value(row_index,col_index) row_list_output.append(non_date_cell) output_worksheet.write(row_index,col_index,non_date_cell) print(row_list_output)output_workbook.save(output_file)
Excel行中的值滿足某個條件
pandas版本 import pandas as pdimport sysinput_file='sales_2013.xlsx'output_file='gp.xls'data_frame=pd.read_excel(input_file,'january_2013',index_col=None)data_frame_value_meets_condition=data_frame[data_frame['Sale Amount'].astype(float) > 1400.0]writer=pd.ExcelWriter(output_file)data_frame_value_meets_condition.to_excel(writer,sheet_name='jan_13_output',index=False)writer.save()
Excel行中的值屬于某個集合
Excel行中的值匹配某個表達(dá)式 import pandas as pdinput_file='sales_2013.xlsx'output_file='pandas_row_value_matches_re.xls'data_frame=pd.read_excel(input_file,'january_2013',index_col=None)data_frame_value_matches_pattern=data_frame[data_frame['Customer Name'].str.match('J')]#或者data_frame_value_matches_pattern=data_frame[data_frame['Customer Name'].str.startswith('J')]writer=pd.ExcelWriter(output_file)data_frame_value_matches_pattern.to_excel(writer,sheet_name='jan_13_output',index=False)writer.save()
Excel基于索引選取特定的列
Excel基于列標(biāo)題選取 import pandas as pdinput_file='sales_2013.xlsx'output_file='pandas_column_title_select.xls'data_frame=pd.read_excel(input_file,'january_2013',index_col=None)data_frame_column_by_name=data_frame.loc[:,['Customer ID','Purchase Date']]writer=pd.ExcelWriter(output_file)data_frame_column_by_name.to_excel(writer,sheet_name='jan_13_output',index=False)writer.save()
工作表計數(shù)以及每個工作表中的行列計數(shù)
在一個Excel文件所有工作表中選取特定行 import pandas as pdinput_file='sales_2013.xlsx'output_file='all_sheeet_column_title.xls'data_frame=pd.read_excel(input_file,sheet_name=None,index_col=None)row_output=[]for worksheet_name , data in data_frame.items(): row_output.append(data[data['Sale Amount'].astype(float) >2279.0])filtered_rows=pd.concat(row_output,axis=0,ignore_index=True)writer=pd.ExcelWriter(output_file)filtered_rows.to_excel(writer,sheet_name='sale_amount_gt200',index=False)writer.save()
在一個Excel所有工作表中選取特定列
在Excel工作簿中讀取一組工作表 import pandas as pdimport sysinput_file='sales_2013.xlsx'output_file='pandas_value_meets_condition_set_of_.xls'my_sheets = ['january_2013','february_2013'] #按照名字#my_sheets = [0,1] 按照索引threshold = 1900.0data_frame = pd.read_excel(input_file, sheet_name=my_sheets, index_col=None)row_list = []for worksheet_name, data in data_frame.items(): row_list.append(data[data['Sale Amount'].replace('$', '').replace(',', '').astype(float) > threshold])filtered_rows = pd.concat(row_list, axis=0, ignore_index=True)writer = pd.ExcelWriter(output_file)filtered_rows.to_excel(writer, sheet_name='set_of_worksheets', index=False)writer.save()
將多個工作簿中的多個工作表整合到一個Excel中
為每個工作簿和工作表計算總數(shù)和平均值 import pandas as pdimport globimport osinput_path = './'output_file = 'pandas_sum_average_multiple_workbooks.xls'all_workbooks = glob.glob(os.path.join(input_path, '*.xls*'))data_frames = []for workbook in all_workbooks: all_worksheets = pd.read_excel(workbook, sheet_name=None, index_col=None) workbook_total_sales = [] workbook_number_of_sales = [] worksheet_data_frames = [] worksheets_data_frame = None workbook_data_frame = None for worksheet_name, data in all_worksheets.items(): total_sales = pd.DataFrame( [float(str(value).strip('$').replace(',', '')) for value in data.ix[:, 'Sale Amount']]).sum() number_of_sales = len(data.loc[:, 'Sale Amount']) average_sales = pd.DataFrame(total_sales / number_of_sales) workbook_total_sales.append(total_sales) workbook_number_of_sales.append(number_of_sales) data = {'workbook': os.path.basename(workbook), 'worksheet': worksheet_name, 'worksheet_total': total_sales, 'worksheet_average': average_sales} worksheet_data_frames.append( pd.DataFrame(data, columns=['workbook', 'worksheet', 'worksheet_total', 'worksheet_average'])) worksheets_data_frame = pd.concat(worksheet_data_frames, axis=0, ignore_index=True) workbook_total = pd.DataFrame(workbook_total_sales).sum() workbook_total_number_of_sales = pd.DataFrame(workbook_number_of_sales).sum() workbook_average = pd.DataFrame(workbook_total / workbook_total_number_of_sales) workbook_stats = {'workbook': os.path.basename(workbook), 'workbook_total': workbook_total, 'workbook_average': workbook_average} workbook_stats = pd.DataFrame(workbook_stats, columns=['workbook', 'workbook_total', 'workbook_average']) #workbook_data_frame == worksheets_data_frame + workbook_stats workbook_data_frame = pd.merge(worksheets_data_frame, workbook_stats, on='workbook', how='left') data_frames.append(workbook_data_frame)all_data_concatenated = pd.concat(data_frames, axis=0, ignore_index=True)writer = pd.ExcelWriter(output_file)all_data_concatenated.to_excel(writer, sheet_name='sums_and_averages', index=False)writer.save()
|
|