如何在合并文件之间添加空行

时间:2016-04-29 11:00:37

标签: python pandas

我有几个我设法合并的CSV文件。但是,我需要在每个文件合并时在它们之间添加一个空行,这样我知道在那一点开始一个不同的文件。尝试了一切。请帮忙。

import os
import glob
import pandas

def concatenate(indir="C:\\testing", outfile="C:\\done.csv"):
    os.chdir(indir)
    fileList=glob.glob("*.csv")
    dfList=[]
    colnames=["Creation Date","Author","Tweet","Language","Location","Country","Continent"]
    for filename in fileList:
        print(filename)
        df=pandas.read_csv(filename, header=None)
        ins=df.insert(len(df),'\n')
        dfList.append(ins)

    concatDf=pandas.concat(dfList,axis=0)
    concatDf.columns=colnames
    concatDf.to_csv(outfile,index=None)

1 个答案:

答案 0 :(得分:1)

这是一个示例脚本。您可以将loc方法与enlarge the DataFrame中不存在的密钥一起使用,并设置新行的值。

最简单的解决方案似乎是创建一个模板DataFrame以用作分隔符,并根据需要设置值。然后只需将其插入数据框列表即可在适当的位置连接。

最后,我删除了chdir,因为glob可以在任何路径中进行搜索。

import glob
import pandas


def concatenate(input_dir, output_file_name):
    file_list=glob.glob(input_dir + "/*.csv")

    column_names=["Creation Date"
        , "Author"
        , "Tweet"
        , "Language"
        , "Location"
        , "Country"
        , "Continent"]

    # Create a separator template
    separator = pandas.DataFrame(columns=column_names)
    separator.loc[0] = [""]*7

    dataframes = []
    for file_name in file_list:
        print(file_name)
        if len(dataframes):
            # The list is not empty, so we need to add a separator
            dataframes.append(separator)
        dataframes.append(pandas.read_csv(file_name))

    concatenated = pandas.concat(dataframes, axis=0)
    concatenated.to_csv(output_file_name, index=None)
    print(concatenated)


concatenate("input", ".out.csv")

另一种更简单的方法是使用append方法迭代地构建连续的DataFrame

def concatenate(input_dir, output_file_name):
    file_list=glob.glob(input_dir + "/*.csv")

    column_names=["Creation Date"
        , "Author"
        , "Tweet"
        , "Language"
        , "Location"
        , "Country"
        , "Continent"]

    concatenated = pandas.DataFrame(columns=column_names)
    for file_name in file_list:
        print(file_name)
        if len(concatenated):
            # The list is not empty, so we need to add a separator
            concatenated.loc[len(concatenated)] = [""]*7
        concatenated = concatenated.append(pandas.read_csv(file_name))

    concatenated.to_csv(output_file_name, index=None)
    print(concatenated)

我用3个输入CSV文件测试了脚本:

<强>输入/ 1.csv

Creation Date,Author,Tweet,Language,Location,Country,Continent
2015-12-17,foo,Hello,EN,London,UK,Europe
2015-12-18,bar,Bye,EN,Manchester,UK,Europe
2015-12-28,baz,Hallo,DE,Frankfurt,Germany,Europe

<强>输入/ 2.csv

Creation Date,Author,Tweet,Language,Location,Country,Continent
2016-01-09,bar,Tweeeeet,EN,New York,USA,America
2016-01-09,cat,Miau,FI,Helsinki,Finland,Europe

<强>输入/ 3.csv

Creation Date,Author,Tweet,Language,Location,Country,Continent
2018-12-12,who,Hello,EN,Delhi,India,Asia

当我运行它时,以下输出被写入控制台:

控制台输出(使用concat)

input\1.csv
input\2.csv
input\3.csv
  Creation Date Author     Tweet Language    Location  Country Continent
0    2015-12-17    foo     Hello       EN      London       UK    Europe
1    2015-12-18    bar       Bye       EN  Manchester       UK    Europe
2    2015-12-28    baz     Hallo       DE   Frankfurt  Germany    Europe
0
0    2016-01-09    bar  Tweeeeet       EN    New York      USA   America
1    2016-01-09    cat      Miau       FI    Helsinki  Finland    Europe
0
0    2018-12-12    who     Hello       EN       Delhi    India      Asia

较短变体的控制台输出略有不同(请注意第一列中的索引),但这对生成的CSV文件没有影响。

控制台输出(使用追加)

input\1.csv
input\2.csv
input\3.csv
  Creation Date Author     Tweet Language    Location  Country Continent
0    2015-12-17    foo     Hello       EN      London       UK    Europe
1    2015-12-18    bar       Bye       EN  Manchester       UK    Europe
2    2015-12-28    baz     Hallo       DE   Frankfurt  Germany    Europe
3
0    2016-01-09    bar  Tweeeeet       EN    New York      USA   America
1    2016-01-09    cat      Miau       FI    Helsinki  Finland    Europe
6
0    2018-12-12    who     Hello       EN       Delhi    India      Asia

最后,这就是它生成的输出CSV文件的样子:

<强> out.csv

Creation Date,Author,Tweet,Language,Location,Country,Continent
2015-12-17,foo,Hello,EN,London,UK,Europe
2015-12-18,bar,Bye,EN,Manchester,UK,Europe
2015-12-28,baz,Hallo,DE,Frankfurt,Germany,Europe
,,,,,,
2016-01-09,bar,Tweeeeet,EN,New York,USA,America
2016-01-09,cat,Miau,FI,Helsinki,Finland,Europe
,,,,,,
2018-12-12,who,Hello,EN,Delhi,India,Asia