2017-04-14 4 views
0

私は2つのスプレッドシートを結合しようとしている簡単な例を作りました。目的は、3つの列として '都市名'、 '州'、および '人口'を含むスプレッドシートを作成することです。私はそれを行う方法は辞書を使用することだと思う。辞書を使用してExcelスプレッドシートを結合する

私は自分でそれをやったことがあり、これは私がこれまで持っていたものです。

code data

+2

あなたの質問ではなく、画像などのテキストとしてあなたのコードとデータを記載してください。 –

+0

最も簡単な方法は、 'pandas.read_excel'を使って2つの' DafaFrames'を取得し、次にこれらをマージすることです –

答えて

3

あなたはパンダのパッケージを知っていますか?

excelファイルのデータをDataFrameに読み取ってpandas.read_excelと入力し、Name of City列の2つのデータフレームをマージすることができます。ここで

はパンダを使用する方法を簡単に合流する2つのデータフレームを示す簡単な例です:

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 
0

おそらく、これ?

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 
# i.e. 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) 

How to concatenate three excels files xlsx using python?

関連する問題