Python 提取唯一的 CSV 行

标签 python csv set unique

我试图在 Python 中获取 CSV 中每一行的第一次出现。但是,我面临一个问题。我的 CSV 文件如下所示:

1,2,3,a,7,5,y,0
1,2,3,a,3,5,y,8
1,2,3,a,5,3,y,7
1,2,3,d,7,5,n,0
1,2,3,d,3,5,n,8
1,2,3,d,5,3,n,7
2,3,4,f,4,6,y,9
2,3,4,f,5,6,y,9
2,3,4,f,7,3,y,9
2,3,4,e,3,5,n,9
2,3,4,e,0,7,n,9
2,3,4,e,5,8,n,9

我尝试通过这种方式根据其中一列获取第一次出现的唯一值。

def unique():
    rows = list(csv.reader(open('try.csv', 'r'), delimiter=','))
    columns = zip(*rows)
    uniq = set(columns[1])

    indexed = defaultdict(list)

    for x in uniq:
        i = columns[1].index(x)
        indexed[i] = rows[i]

    return indexed

它适用于一个唯一的列值集。然而,

  1. 我想将列[1] 和列[6] 设置为唯一值。
  2. 棘手的部分是 columns[6] 总是 y 或 n。如果我设置它,它只会返回前 y 和 n 列。我想获得所有同时具有 columns[1] 和 columns[6] 的列。对于每个 columns[2] 值,我需要第一个出现的 y 和 n 行。对不起,我的描述不佳。所以基本上,我希望我的输出是这样的:
1,2,3,d,7,5,n,0,a
2,3,4,e,3,5,n,9,f

最佳答案

您的代码还有一些改进空间,但我不想深入重写它,因为您几乎是对的。 “关键”点是您需要一个复合键。这是必须唯一的 (r[1],r[6])。此外,我冒昧地使用了OrderedDict。用于快速查找,但保留行顺序。

import csv
import collections

def unique():
    rows = list(csv.reader(open('try.csv', 'r'), delimiter=','))
    result = collections.OrderedDict()
    for r in rows:
        key = (r[1],r[6])  ## The pair (r[1],r[6]) must be unique
        if key not in result:
            result[key] = r

    return result.values()

from pprint import pprint
pprint(unique())

制作:

[['1', '2', '3', 'a', '7', '5', 'y', '0'],
 ['1', '2', '3', 'a', '7', '5', 'n', '0'],
 ['2', '3', '4', 'f', '4', '6', 'y', '9'],
 ['2', '3', '4', 'f', '3', '5', 'n', '9']]

关于Python 提取唯一的 CSV 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25554286/

相关文章:

python - Docker jupyter notebook 使用容器 id 作为 ip,localhost

c++ - 将换行符 (\n) 添加到 CSV 文件中?

java - 根据其属性从 Set 中选择一个元素

c++ - 在插入集合 C++ 之前比较字符串

python - 查找列表(从 Excel 导入)中的最高/最低行中的内容 - Python3

python pygame让外星人群体移动

angularjs - 在 nodejs 中从服务器下载 .zip 文件

java - 查找集合的所有子集 (PowerSet)

Python:深入获取项目? (设置图书馆?)

linux - 合并 Google Cloud Storage 中的文件