【问题标题】:Combine 2 csv files with same no. of features Python合并 2 个相同编号的 csv 文件。功能 Python
【发布时间】:2014-01-29 07:13:30
【问题描述】:

我有 2 个包含许多观察结果的文件。我需要垂直合并它们。例如: Csv A 包含一些人的关注数据:

Sr.no  Name, Age , Sex, Weight, Height  
1.     A,    12,   M,   40,     4ft  
2.     B,    13,   F,   35,     3.9ft       
3.     C,    15,   F,   45,     4.2ft

Csv B 包含:

1. D,20,M,55,5.3ft   
2. E,22,F,53,5.0ft

我希望输出看起来像:

1. A, 12, M, 40, 4ft  
2. B, 13, F, 35, 3.9ft   
3. C, 15, F, 45, 4.2ft   
4. D, 20, M, 55, 5.3ft   
5. E, 22, F, 53, 5.0ft  

试过a.merge,但不知道如何通过参数。
是的,我忘了提到索引。合并后的 csv 应将观察结果显示为 1,2,3,4,5 。 Csv A 的索引为 1,2,3,而 Csv B 的索引为 1,2。合并后,结果索引为1,2,3,4,5..

【问题讨论】:

  • 为什么不追加这两个文件呢?结果仍然是有效的 CSV 文件。
  • 那么索引呢?都从 1 开始。所以我希望第二个索引继续使用 Csv A 的索引
  • 文件中没有索引,对吧?所以python应该正确索引它。
  • 我不明白有什么困难?以追加模式打开文件 A 并将 B 中的行写入其中。
  • 实际上我正在处理的文件中有一个索引。我忘了在上面的例子中提到它。只需检查一下,我已经在上面编辑了我的问题。

标签: python csv merge


【解决方案1】:

也许这就是你想要的:

A = open('A.csv','r')
B = open('B.csv','r')
out = open('out.csv','w')
i = 0
# writing A file
for line in A:
    if i==0: # This is to handle the headers line in csv A
        out.write(line)
    else:
        out.write("%s. %s" %(i,line[line.find('.')+1:]))
    i = i+1

# This is to handle where there is not end-of-line at the end of A.csv
if not line.endswith("\n"):
    out.write("\n")

# writing B file
for line in B:
    out.write("%s. %s" %(i,line[line.find('.')+1:]))
    i = i+1
A.close()
B.close()
out.close()

【讨论】:

    【解决方案2】:

    试试下面的代码:

    import csv
    from itertools import chain
    
    with open('a.csv') as a, open('b.csv') as b, open('out.csv', 'w') as out:
        a = csv.reader(a)
        b = csv.reader(b)
        out = csv.writer(out)
        for i, row in enumerate(chain(a, b), 1):
            row[0] = i
            out.writerow(row)
    

    【讨论】:

      【解决方案3】:

      一般来说,我会说在合并期间忽略索引并在运行时再次读取文件时创建自己的索引(仅通过计算行数)可能会更快。 然后,谈论file.merge(),查看这篇关于pandasMerge, join, and concatenate 的文章。 Merge 不是您要找的东西。它可以像在数据库中那样合并 CSV 文件。您可以将其弯曲以适合您的目的,但我认为最好的方法就是使用以下简单代码。

      我建议(对于 Python 2.5 及更高版本)使用 with 打开文件。 (Python's with statement)。

      import shutil;
      
      def merge():
          print '*** Merging started ***';
          # opening all the files using with
          with open('fileA.csv','r') as fileA, open('fileB.csv','r') as fileB, open('fileOutput.csv','w') as output:
              # if all the files start by index no. 1, then you don't need to copy line by line the whole file and you can just use a copy of whole file
              # you just need to count the number of lines in order to know which number to use for fileB
              lines_counter = 0;
              for line in fileA:
                  lines_counter += 1;
      
              # only copy the file fileA in fileOutput
              shutil.copyfile('fileA.csv','fileOutput.csv');
      
              # if the last line of fileA was not ended by end of line, append it
              if not line.endswith('\n'):
                  output.write('\n');
      
              # copy all the lines of fileB and add the index which belongs to the line    
              for line in fileB:
                  lines_counter += 1;
                  line_without_index = line[line.find('.'):];
                  output.write('{}{}'.format(str(lines_counter),line_without_index));
      
          print '*** Merging finished ***';
      
      merge();
      

      已编辑:

      shutil 不起作用时,您仍然可以删除

      shutil.copyfile('fileA.csv','fileOutput.csv');
      

      并在第一个 for 循环中添加一行,因此第一个 for 循环如下所示:

      for line in fileA:
          lines_counter += 1;
          output.write(line);
      

      它应该以相同的方式工作。性能上可能只有很小的差异。但我想这没什么大不了的。

      【讨论】:

      • 嗨,谢谢你的代码,但 shutil 模块不可调用。我该如何安装它? (或导入)?
      • ------------------------------------------ --------------------------------- TypeError Traceback(最近一次调用最后一次)() 22 lines_counter += 1; 23 line_without_index = line[line.find('.'):]; ---> 24 output.write('{}{}'.format(str(lines_counter),line_without_index)); 25 26 print '*** 合并完成 ***'; TypeError:“模块”对象不可调用***合并开始***
      • 很抱歉。您可以在代码开头通过import shutil 导入shutil。我编辑了代码。我希望现在没事。
      • 你使用什么版本的 Python?当我测试它时,它似乎没问题,shutil 应该是 Python 中的标准模块。
      【解决方案4】:

      我明白了.. 不过它很简单。你需要做的就是
      FileC = FileA.append(FileB ,ignore_index = True)

      索引会以适当的方式自动重新调整。虽然索引从 0 开始,但这不是问题,因为每个观测值都有其唯一的索引号。

      【讨论】:

        猜你喜欢
        • 2016-05-01
        • 2020-10-25
        • 2015-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-15
        • 1970-01-01
        相关资源
        最近更新 更多