2016-07-26 12 views
1

私はPythonには新しく、これを始めるにはいくつかの難しさがありました。私はPython 3を使用しています。Pythonを使用してcsvファイルから既存のxlsファイルに複数の列をコピーする

私はグーグルでこれを助けるかなりの数のPythonモジュールを見つけましたが、ここではより明確な答えを期待していました。だから、基本的に、私はcsvファイルから特定の列、すなわちG、H、I、K、Mを読む必要があります。必要なものは連続していません。

これらの列をcsvファイルから読み込んで、既存のxlsの空の列にデータを転送する必要があります。

私はopenpyxlを調べましたが、csv/xlsファイルでは機能していないようです.xlsxのみです。 xlwtモジュールを使ってこれを行うことはできますか?

どのモジュールが私の使用目的に最も適しているかについてのご指摘をいただければ幸いです。その間、私はxlwt/xlrdで周りに微妙に変わるつもりです。

+0

xlwt/xlrd私は使用しました。彼らは私のために正常に動作するようです。 Pythonはcsvreaderを持っています –

+0

私は言及するのを忘れました。 csvファイルのこれらの各列には、約9kのエントリがあります。 – Kepler

答えて

2

パンダを使用することをおすすめします。それは、csvとxlsファイルを読み書きする便利な機能を持っています。

import pandas as pd 
from openpyxl import load_workbook 

#read the csv file 
df_1 = pd.read_csv('c:/test/test.csv') 

#lets say df_1 has columns colA and colB 
print(df_1) 

#read the xls(x) file 
df_2=pd.read_excel('c:/test/test.xlsx') 
#lets say df_2 has columns aa and bb 

#now add a column from df_1 to df_2 
df_2['colA']=df_1['colA'] 

#save the combined output 
writer = pd.ExcelWriter('c:/test/combined.xlsx') 
df_2.to_excel(writer) 
writer.save() 

#alternatively, if you want to add just one column to an existing xlsx file: 

#i.e. get colA from df_1 into a new dataframe 
df_3=pd.DataFrame(df_1['colA']) 


#create writer using openpyxl engine 
writer = pd.ExcelWriter('c:/test/combined.xlsx', engine='openpyxl') 

#need this workaround to provide a list of work sheets in the file 
book = load_workbook('c:/test/combined.xlsx') 
writer.book = book 
writer.sheets = dict((ws.title, ws) for ws in book.worksheets) 

column_to_write=16 #this would go to column Q (zero based index) 
writeRowIndex=0 #don't plot row index 
sheetName='Sheet1' #which sheet to write on 

#now write the single column df_3 to the file 
df_3.to_excel(writer, sheet_name=sheetName, columns =['colA'],startcol=column_to_write,index=writeRowIndex) 

writer.save() 
+0

うわー!私は間違いなくこれを試してみましょう!したがって、パンダモジュールには、csvファイルの特定の列を選択してxlsファイルの特定の列に格納する方法がありますか?編集:これらのファイルも、各列の10kエントリのような大量のデータを持っています。 – Kepler

+0

私はcsvとxlsファイルの両方を読むこと、あなたが望む列を結合して、すべてを新しいファイルに保存することをお勧めします。それは可能でしょうか? – jlarsch

+0

ええ、私はうまくいくでしょう。列を結合する方法を調べなければなりません。エントリーの量によって問題が生じるのでしょうか? – Kepler

関連する問題