簡體   English   中英

迭代合並python中的兩個CSV文件

[英]Merge two CSV files in python iteratively

我有一組保存在多個.csv文件中且具有固定列數的數據。 每列對應一個不同的度量。

我想為每個文件添加標題。 標頭對於所有文件都是相同的,並且由三行組成。 這些行中的兩個用於標識其對應的列。

我在想可以將標頭保存在單獨的.csv文件中,然后使用for循環將其與每個數據文件迭代合並。

如何在python中做到這一點? 我是該語言的新手。

是的,您可以使用熊貓輕松做到這一點。 它會比您當前所認為的可能會導致問題的速度更快,更輕松。

將使用三個簡單的命令來讀取,合並並將其放入新文件中,它們是:

pandas.read_csv()
pandas.merge()
pandas.to_csv()

您可以在此處閱讀必須使用的參數以及有關它們的更多詳細信息

for your case you may need first to create new files with
the headers with them. then you would do another loop to
add the rows, but skipping the header. 

import csv
with open("data_out.csv","a") as fout:
    # first file:
    with open("data.csv") as f: # you header file
        for line in f:
            fout.write(line)

    with open("data_2.csv") as f:
        next(f)        # this will skip first line
        for line in f:
          fout.write(line)

而不是運行for循環為多個文件附加兩個文件的方法,一個更簡單的解決方案是將要合並的所有csv文件放入一個文件夾中,然后將路徑提供給程序。 這會將所有csv文件合並為一個csv文件。 (注意:每個文件的屬性必須相同)

import os
import pandas as pd

#give the path to the folder containing the multiple csv files
dirList = os.listdir(path)

#Put all their names into a list
filenames = []
for item in dirList:
    if ".csv" in item:
        filenames.append(item) 

#Create a dataframe and make sure it's empty (not required but safe practice if using for appending)
df1 = pd.Dataframe()
df1.drop(df1.index, inplace=True)

#Convert each file to a dataframe and append it to dataframe df1
for f in filenames:
    df = pd.read_csv(f)
    df1 = df1.append(df)

#Convert the dataframe into a single csvfile
df1.to_csv(csvfile, encoding='utf-8', index=False)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM