2016-12-30 73 views
3

我從聖路易斯弗雷德價格指數數據的50 csv文件,每個文件的格式是這樣的:如何合併csv文件並使用python添加標題行?

enter image description here

我想結合多個CSV文件,並添加報頭的一個多行他們實現了以下格式:

enter image description here

所以我可以存儲在一個CSV文件中的數據,我可以知道有沒有什麼辦法,我可以與Python做呢?

+0

這可以使用Python中的'csv'模塊完成。只是谷歌的例子或閱讀文檔的使用情況。 – sisanared

+0

或者,使用'pandas.read_csv()'讀取每個文件,然後將數據幀連接或合併到一個數據幀中。 – DyZ

回答

3

DATE列的重複沒有意義。除非有特定的目的。另外,在合併時,要特別注意特定行上的數據屬於同一日期。

其更好地利用大熊貓如果你正在使用DATE作爲索引合併和使用OUTER法合併。所以,來自同一日期的值是相同的。

import pandas as pd; 

df1 = pd.read_table('file1.csv', sep=',') 
df2 = pd.read_table('file2.csv', sep=',') 
df3 = pd.read_table('file3.csv', sep=',') 

因此,基本上加載所有文件作爲數據框。然後使用mergereduce函數合併文件。

data_frames = [df1, df2, df3] 

你可以在上面的代碼添加儘可能多的數據幀。

然後合併它們。爲了使屬於同一日期值,您需要合併它的DATE

df_merged = reduce(lambda left,right: pd.merge(left,right,on=['DATE'], 
              how='outer'), data_frames) 

然後合併後的數據寫入到CSV文件。

pd.DataFrame.to_csv(df_merged, 'merged.txt', sep=',', na_rep='.', index=False) 

這應該給你

DATE VALUE1 VALUE2 VALUE3 ....

+0

非常感謝你!!!!! –

+0

你能接受我的回答嗎? – everestial007

+0

明白了,請檢查! –

1

大熊貓是很好的解決方案,但如果你想要一個Python標準庫的解決方案:

import csv 
from itertools import chain 

csv_input_filenames = [ 
    'csvfile1.csv', 
    'csvfile2.csv', 
    'csvfile3.csv', 
] 
csv_output_filename = 'csv_out.csv' 

# get the csv data 
csv_files = [open(file_name) for file_name in csv_input_filenames] 
csv_handles = [csv.reader(csv_file) for csv_file in csv_files] 
rows = (list(chain(*row)) for row in zip(*csv_handles)) 

# write combined output 
with open(csv_output_filename, 'wb') as csv_file: 
    filenames_header = list(chain(
     *zip(csv_input_filenames, [''] * len(csv_input_filenames)))) 

    csv_writer = csv.writer(csv_file) 
    csv_writer.writerow(filenames_header) 

    for row in rows: 
     csv_writer.writerow(row) 

# close input files 
for csv_file in csv_files: 
    csv_file.close() 
1

這將垂直串聯中的所有文件提供的目錄(所以你不必在代碼中指定它們)。這些文件可以有任意數量的列,並且可以處理值中的空格。但是這些文件必須都具有相同的行數。

它只使用模塊csv和os。

import os 
import csv 

dir_base = r'H:\apps\xp\Desktop\localrepo\Temp' 
dir_name = '-test2' 
output_name = 'output.csv' 

path = os.path.join(dir_base, dir_name) 
out_path = os.path.join(dir_base, output_name) 


def _extend(lines, lineno, line): 
    try: 
     lines[lineno].extend(line) 
    except IndexError: 
     lines.append(line) 


def main(): 
    lines = [] 

    # read and generate new file 
    for root, dirs, files in os.walk(path): 
     for f in files: 
      with open(os.path.join(root, f), 'r') as csvfile: 
       f_in = csv.reader(csvfile) 
       for lineno, line in enumerate(f_in, start=1): 
        if lineno == 1: 
         header = [''] * len(line) 
         header[0] = f 
         _extend(lines, 0, header) 
        _extend(lines, lineno, line) 

    # print new file 
    with open(out_path, 'w', newline='\n') as csvfile: 
     csv.writer(csvfile).writerows(lines) 


if __name__ == '__main__': 
    main() 

輸出看起來是這樣的: enter image description here

如果你的「CSV」文件,有其他的分隔符(因此不是技術上的「C」 SV文件),只是改變了代碼csv.reader(csvfile)的這一部分,以指示分隔符,例如,csv.reader(csvfile, delimiter='|')

希望它有幫助!

相關問題