【问题标题】:Merging CSV Files with missing columns in Pandas在 Pandas 中合并缺少列的 CSV 文件
【发布时间】:2015-06-03 06:09:48
【问题描述】:

我是pandaspython 的新手,所以我希望这是有道理的。

我已将网站上的multiple 表解析为multiple CSV files,不幸的是,如果该值不适用于解析的数据,则会从表中省略。因此,我现在拥有包含不同列数的 CSV 文件。

我过去使用过read_csv()to_csv(),当数据干净时,它就像一个魅力,但我被难住了。

如果我首先将所有列标题提供给pandas DF,然后我将每个文件映射到主文件中的列,我认为可能有一种方法可以“map”读取数据。

例如。一旦我使用了read_csv(),然后to_csv() 将查看主合并文件和“map”合并文件中正确列的可用字段。

这是数据的简短版本:

File 1:
ID, Price, Name, 
1, $800, Jim
File 2:
ID, Price, Address, Name
2, $500, 1 Main St., Amanda


Desired Output:
ID, Price, Adress, Name
1, $800, , Jim
2, $500, 1 Main St., Amanda

这是我目前得到的代码。

mypath='I:\\Filepath\\'

#creating list of files to be read, and merged. 
listFiles = []
for (dirpath, dirnames, filenames) in walk(mypath):
    listFiles.extend(filenames)
    break

# reading/writing "master headers" to new CSV using a "master header" file     
headers = pd.read_csv('I:\\Filepath\\master_header.csv', index_col=0)

with open('I:\\Filepath\\merge.csv', 'wb') as f:
        headers.to_csv(f)

def mergefile(filenames):


    try:
    # Creating a list of files read. 
    with open('I:\\Filepath\\file_list.txt', 'a') as f:
        f.write(str(filenames)+'\n')

    os.chdir('I:\\Filepath\\')
    # Reading file to add.
    df = pd.read_csv(filenames, index_col=0)


    # Appending data (w/o header) to the new merged data CSV file. 
    with open('I:\\Filepath\\merge.csv', 'a') as f:


    df.to_csv(f, header=False)


except Exception, e:
    with open('I:\\Filepath\\all_error.txt', 'a') as f:
        f.write(str(e)+'\n')

for eachfilenames in listFiles:
    mergefile(eachfilenames)

这段代码合并了数据,但是由于列数不同,所以放的地方不对……

任何帮助将不胜感激。

【问题讨论】:

  • 它与熊猫无关,但您可能会发现有用stackoverflow.com/questions/26771999/…
  • 您应该在pandas 中进行所有合并,使用DataFrame.joinDataFrame.append 等内容。仅在最后将结果写入文件。这将比通过将零碎单独写入文件来尝试将其拼接在一起要少得多。 pandas很多 用于组合数据的工具,通过这种方式你会错过所有这些工具。

标签: python csv pandas


【解决方案1】:

尝试使用 pandas concat[1] 函数,该函数默认为外连接(所有列都存在,缺失值为 NaN)。例如:

import pandas as pd

# you would read each table into its own data frame using read_csv
f1 = pd.DataFrame({'ID': [1], 'Price': [800], 'Name': ['Jim']})
f2 = pd.DataFrame({'ID': [2], 'Price': [500], 'Address': '1 Main St.', 'Name': ['Amanda']})

pd.concat([f1, f2]) # merged data frame

[1]http://pandas.pydata.org/pandas-docs/stable/merging.html

【讨论】:

    【解决方案2】:

    这是一个完整的示例,演示如何使用concat 加载和合并文件:

    In [297]:
    import pandas as pd
    import io
    t="""ID, Price, Name
    1, $800, Jim"""
    df = pd.read_csv(io.StringIO(t), sep=',\s+')
    t1="""ID, Price, Address, Name
    2, $500, 1 Main St., Amanda"""
    df1 = pd.read_csv(io.StringIO(t1), sep=',\s+')
    pd.concat([df,df1], ignore_index=True)
    
    Out[297]:
          Address  ID    Name Price
    0         NaN   1     Jim  $800
    1  1 Main St.   2  Amanda  $500
    

    请注意,我通过 ignore_index=True 否则您将获得重复的索引条目,我认为这不是您想要的,而且我假设在您的“文件 1”的原始数据样本中,您实际上并没有尾随标题行中的逗号:ID, Price, Name, 所以我从上面的代码中删除了它

    【讨论】:

    • 感谢您为我指明正确的方向。我能够让它工作。
    猜你喜欢
    • 1970-01-01
    • 2018-02-23
    • 1970-01-01
    • 2018-06-11
    • 2020-11-18
    • 2017-07-23
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    相关资源
    最近更新 更多