Python操作Excel把數據分給sheet
需求:根據country列的不同值,將內容分到不同sheet
方法一:
讀取原Excel,根據country列將不同的內容放到不同的sheet,并根據國家名稱命名,將結果放到新的輸出文件中。
#!/usr/bin/env python3#讀取Excel文件import pandas as pdinput_file = 'F://python入門//數據2//appname_test.xlsx'output_file = 'F://python入門//數據2//output.xlsx'data_frame = pd.read_excel(input_file,sheet_name=’sum1’,index_col = None)data_frame_country = data_frame[’country’]category_countory = set(data_frame_country)writer = pd.ExcelWriter(output_file)for country in list(category_countory): df = data_frame[data_frame[’country’] == country] df.to_excel(writer, sheet_name= country ,index=False)writer.save()
結果,生成了output.xlsx,將appname_test.xlsx中的匯總數據根據不同國家分到了不同sheet:
方法二:
讀取原Excel,根據country列將不同的內容放到不同的CSV文件,并根據國家名稱命名。
#!/usr/bin/env python3#讀取Excel文件import pandas as pdinput_file = 'F://python入門//數據2//appname_test.xlsx'data_frame = pd.read_excel(input_file,sheet_name=’sum1’,index_col = None)data_frame_country = data_frame[’country’]category_countory = set(data_frame_country)for country in list(category_countory): df = data_frame[data_frame[’country’] == country] df.to_csv('F:/python入門/數據2/table_{}.csv'.format(country), encoding='gbk', index=False)
結果生成四個csv文件:
以table_繁體中文為例:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: