【问题标题】:Merge tow excel file with some parameters合并两个带有一些参数的excel文件
【发布时间】:2021-01-01 17:15:34
【问题描述】:

【问题讨论】:

  • 所以要合并这两个文件?
  • 是的,但不只是合并拖车文件,我还想合并一些值而忽略其他的
  • .csv 文件或 excel .xls/xlsx?

标签: python excel pandas merge sum


【解决方案1】:

下面是一个如何迭代多个文件并组合值的示例。您将看到如何打开文件、读取文件和操作数据。下面的例子是一个粗略的例子,可以做得更优雅,但如果没有适当的上下文,这可能会让你有一个正确的开始。该示例假定存在并且总是只有三列。我在下面的输出显示只是将示例最终值打印出来,但您可以轻松地将它们写入一个新文件。

#create dict to track values
dict = {}
files = ['file1.csv', 'file2.csv']

for file in files:
  with open(file) as rfile:
    next(rfile) #skip first line
    
    for row in rfile: 
      row = row.split(' ')
      
      #get rows column values
      a_value = float(row[0].strip())
      b_value = float(row[1].strip())
      c_value = float(row[2].strip())
      
      #a column value isn't in dictionary
      if a_value not in dict.keys(): 
        dict[a_value] = [b_value, c_value]
      else: 
        dict[a_value][1] += c_value

    

print("A B C")
for key, val in dict.items():
  print(key,val[0],val[1])

上面的例子:

A B C
112.0 5.0 300.0
110.0 10.0 300.0
1111.0 2.0 2222.0
115.0 2.0 400.0
116.0 2.0 122.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-15
    • 2022-11-09
    • 2021-06-28
    • 2013-05-23
    相关资源
    最近更新 更多