【问题标题】:Count Identical items in csv and append the count as column计数 csv 中的相同项目并将计数附加为列
【发布时间】:2018-01-18 05:09:47
【问题描述】:

我有像下面这样的inputs.csv

苹果 400
香蕉 401
芒果430
橙色 440
香蕉 401
橙色 440
芒果430
苹果 400
橙色 440
香蕉401

我想要像 output.csv 这样的输出

苹果 400 2
香蕉 401 3
芒果 430 2
橙色 440 3

即我们应该计算该特定类型的项目数并将计数插入第三列

我试过下面的代码

with open('new.csv','r') as csvinput:
  with open('update.csv', 'w') as csvoutput:
    writer = csv.writer(csvoutput)
    reader = csv.reader(csvinput)

    all = []
    row = next(reader)
    row.append("No.of.Rows")
    all.append(row)

    cn = Counter(map(itemgetter(0), reader))

    for k, v in cn.items():
         print("k compared is::",k)
         with open('new.csv','r') as csvinput:
              reader = csv.reader(csvinput)
              for row in reader:
                  print("Executing inner loop")
                  print("row value compared is ::",row[0])
                  if k == row[0] :
                     print("matched")
                     row.append(v)
                     all.append(row)
                     break
    writer.writerows(all)

使用此代码它可以工作,但我担心 new.csv 文件将被打开并读取 k 次,所以有没有比这更好的解决方案

【问题讨论】:

标签: python python-3.x python-2.7


【解决方案1】:

如果您愿意使用 pandas ,您可以将 csv 加载到数据框中并使用以下三行代码轻松操作。

有关详细信息,请参阅 pandas 文档。

import pandas as pd

df = pd.read_csv('input.csv', sep=' ', header=None)
df.groupby([0,1]).size().to_csv('output.csv')

一旦文件直接加载到数据框df,它会列出如下数据

>>> df
        0    1
0   apple  400
1  banana  401
2   mango  430
3  orange  440
4  banana  401
5  orange  440
6   mango  430
7   apple  400
8  orange  440
9  banana  401

在按列分组并计数后,在一行中给出所需的计算。

>>> df.groupby([0,1]).size()
0       1  
apple   400    2
banana  401    3
mango   430    2
orange  440    3
dtype: int64
>>> 

【讨论】:

    【解决方案2】:

    你可以简化你的方法:

    from collections import Counter
    
    with open('inputs.csv') as in_file, open('outputs.csv', 'w') as out_file:
        counts = Counter(map(str.strip, in_file))
    
        for k, v in sorted(counts.items()):
            out_file.write(k + ' ' + str(v) + '\n')
    

    如图所示,只需要在读取文件和写入文件时调用open()即可。如果您想读取一次文件,请致电open() 一次。我不知道你为什么要多读几遍。这也适用于写入文件。

    那么如果你想查看一次outputs.csv的内容,你可以在with语句之外调用这个:

    print(open('outputs.csv').read())
    

    哪些输出:

    apple 400 2
    banana 401 3
    mango 430 2
    orange 440 3
    

    注意:您在问题中的文件不是.csv 文件,因为它们不是逗号分隔的。将它们作为.txt 文件在这里会很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 2018-08-30
      • 1970-01-01
      • 2020-08-28
      • 2016-03-12
      • 1970-01-01
      相关资源
      最近更新 更多