收集 CSV 文件中唯一元素的所有索引并将它们填充成一行

Collecting all the indices of unique elements in CSV file and populating them in a row

我在 CSV 文件中有一组这样的数据:

[['1', '1.5', '1', '2', '1.5', '2'],
 ['2', '2.5', '3', '2.5', '3', '2.5'],
 ['3', '2.5', '1.5', '1', '1', '3'],
 ['1.5', '1', '2', '2', '2', '2.5'],
 ['1.5', '1.5', '1', '2.5', '1', '3']]

我想查找此数据中按升序列出的所有唯一条目。我试过这段代码:

import csv
import numpy 

    dim1=[]                                                                        
    with open('D:/TABLE/unique_values.csv') as f1:
        for rows in f1.readlines():
            dim1.append(rows.strip().split(','))    
            
            
    uniqueValues = numpy.unique(dim1)
    print('Unique Values : ',uniqueValues)

它给了我这个输出:

Unique Values :  ['1' '1.5' '2' '2.5' '3']

我想在 CSV 文件的列中列出这些独特的条目,并希望将它们的 运行 索引写在针对每个独特条目的一行中。下面显示了所需的示例输出。

示例输出

我尝试过其他 numpy 函数,但它们只 return 唯一条目的第一次出现。另外,我看过其他相关帖子,但它们不会连续填充每个唯一元素的 运行 索引。

这对于标准库中的一些函数来说相当简单:collections.defaultdictcsv.reader,和 itertools.count。类似于:

import csv
import collections 
import itertools

data = collections.defaultdict(list)                                                                        

index = itertools.count(1)
with open('D:/TABLE/unique_values.csv') as f1:
    reader = csv.reader(f1)

    for row in reader:
        for value in row:
            data[value].append(next(index))    
            
for unique_value, indices in data.items():
    print(f"{unique_value}:", *indices)