结合Excel电子表格使用字典

我已经做了一个简单的例子,我试图合并两个电子表格。 目的是创build一个电子表格,其中包括“城市名称”,“州”和“人口”三栏。 我认为这样做的方式是使用字典。

我已经自己去了,这是我迄今为止。

代码 数据

你知道pandas包吗?

您可以使用pandas.read_excel将数据从excel文件读取到pandas.read_excel ,然后合并“ Name of City列中的两个数据pandas.read_excel

下面是一个简短的例子,展示了如何使用pandas来合并两个数据框:

 In [1]: import pandas as pd In [3]: df1 = pd.DataFrame({'Name of City': ['Sydney', 'Melbourne'], ...: 'State': ['NSW', 'VIC']}) In [4]: df2 = pd.DataFrame({'Name of City': ['Sydney', 'Melbourne'], ...: 'Population': [1000000, 200000]}) In [5]: result = pd.merge(df1, df2, on='Name of City') In [6]: result Out[6]: Name of City State Population 0 Sydney NSW 1000000 1 Melbourne VIC 200000 

也许这个?

 import os import os.path import xlrd import xlsxwriter file_name = input("Decide the destination file name in DOUBLE QUOTES: ") merged_file_name = file_name + ".xlsx" dest_book = xlsxwriter.Workbook(merged_file_name) dest_sheet_1 = dest_book.add_worksheet() dest_row = 1 temp = 0 path = input("Enter the path in DOUBLE QUOTES: ") for root,dirs,files in os.walk(path): files = [ _ for _ in files if _.endswith('.xlsx') ] for xlsfile in files: print ("File in mentioned folder is: " + xlsfile) temp_book = xlrd.open_workbook(os.path.join(root,xlsfile)) temp_sheet = temp_book.sheet_by_index(0) if temp == 0: for col_index in range(temp_sheet.ncols): str = temp_sheet.cell_value(0, col_index) dest_sheet_1.write(0, col_index, str) temp = temp + 1 for row_index in range(1, temp_sheet.nrows): for col_index in range(temp_sheet.ncols): str = temp_sheet.cell_value(row_index, col_index) dest_sheet_1.write(dest_row, col_index, str) dest_row = dest_row + 1 dest_book.close() book = xlrd.open_workbook(merged_file_name) sheet = book.sheet_by_index(0) print "number of rows in destination file are: ", sheet.nrows print "number of columns in destination file are: ", sheet.ncols 

这似乎也应该工作。

 import pandas as pd # filenames excel_names = ["xlsx1.xlsx", "xlsx2.xlsx", "xlsx3.xlsx"] # read them in excels = [pd.ExcelFile(name) for name in excel_names] # turn them into dataframes frames = [x.parse(x.sheet_names[0], header=None,index_col=None) for x in excels] # delete the first row for all frames except the first # ie remove the header row -- assumes it's the first frames[1:] = [df[1:] for df in frames[1:]] # concatenate them.. combined = pd.concat(frames) # write it out combined.to_excel("c.xlsx", header=False, index=False) 

如何使用python连接三个excels文件xlsx?