【问题标题】:Filter unique values in csv and add count as a new column过滤 csv 中的唯一值并将计数添加为新列
【发布时间】:2020-08-28 00:28:15
【问题描述】:

我有一个非常大的 csv(或多或少 5000 万条记录)文件,其中包含不同的列,例如:

id, state, city, origin, destination, url, type

在这个文件中,我想检查每个重复的值,我的意思是所有具有完全相同列值的行,删除重复项,然后添加一个具有重复编号的新列。

例如,如果我有

id, state, city, origin, destination, url, type
1, NY, NY, manhattan, times square, http:ny.com, taxi
1, NY, NY, manhattan, times square, http:ny.com, taxi
1, NY, NY, manhattan, times square, http:ny.com, taxi
1, NY, NY, manhattan, times square, http:ny.com, taxi

我想输出这个

id, state, city, origin, destination, url, type, count
1, NY, NY, manhattan, times square, http:ny.com, taxi, 4

其中 count 是此列重复的次数。 我知道一些 javascript 但不知道 Python,但是我愿意使用任何工具,只要我可以使用新值和列创建一个新文件。

【问题讨论】:

  • pandas稍微研究一下,你会发现它适合你的ABC问题。
  • show us你尝试了什么
  • @Tserenjamts 不要一看到 CSV 文件就盲目地使用 pandas。将其作为文本处理有时可能更简单......
  • @KooiInc 我没试过,因为我不知道从哪里开始 :)
  • @Tserenjamts 谢谢,我会看看我是否可以了解熊猫

标签: javascript python csv data-manipulation


【解决方案1】:

如果没有间距问题,您可以将文件作为文本处理:

with open('input.csv') as fdin, open('output.csv', 'w', newline='\r\n') as fdout:
    header = next(fdin).strip()
    lines = {}
    for line in fd:
            line = line.strip()
            n = lines.get(line.strip(), 0)
            lines[line.strip()] = n+1
    print(header, file=fdout)
    for line, n in lines.items():
            print(line, n, file=fdout)

这里的好处是,如果有很多重复,你只将唯一的行存储在内存中。

如果重复是连续的,那就更简单了,只有最后一行会存储在内存中。

【讨论】:

    【解决方案2】:

    如果您将 csv 读入名为 df 的 pandas DataFrame 中,您可以应用以下内容。

    df.groupby(df.columns.to_list()).size()
    

    【讨论】:

      【解决方案3】:

      如果你愿意使用pandas 那么,使用:

      import pandas as pd
      
      df = pd.read_csv("data.csv") # read the csv file as dataframe
      
      data = (
          df.groupby(df.columns.tolist())
          .size()
          .rename("count")
          .to_frame().reset_index()
      )
      
      data.to_csv("output.csv", index=False) # exports the dataframe as csv file.
      

      这将生成一个名为 output.csvcsv 文件,如下所示:

      id, state, city, origin, destination, url, type,count
      1, NY, NY, manhattan, times square, http:ny.com, taxi,4
      ....
      ....
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-16
        • 2019-04-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-22
        相关资源
        最近更新 更多