分析主键不是uniqu的CSV中的唯一值

2024-04-26 23:17:32 发布

您现在位置:Python中文网/ 问答频道 /正文

这看起来很琐碎。一般来说,我会做如下的事情:

results = []
reader = csv.reader(open('file.csv'))
for line in reader:  # iterate over the lines in the csv
    if line[1] in ['XXX','YYY','ZZZ']:  # check if the 2nd element is one you're looking for
        results.append(line)    # if so, add this line the the results list

然而,我的数据集并不是简单的格式化。如下所示:

Symbol,Values Date
XXX,8/2/2010
XXX,8/3/2010
XXX,8/4/2010
YYY,8/2/2010
YYY,8/3/2010
YYY,8/4/2010
ZZZ,8/2/2010
ZZZ,8/3/2010
ZZZ,8/4/2010

实际上,我要做的是解析列表中每个唯一符号的第一个日期,这样我就可以得到以下结果:

XXX,8/2/2010
YYY,8/2/2010
ZZZ,8/2/2010

Tags: csvtheinforiflineopen事情
2条回答

Pandas可能会有帮助。;—)

import pandas
pandas.read_csv('file.csv').groupby('Symbol').first()

下面是一个使用一组已找到的第一个元素的简单解决方案:

results = []
reader = csv.reader(open('file.csv'))
already_done = set()
for line in reader:  # iterate over the lines in the csv
    if line[1] in ['XXX','YYY','ZZZ'] and line[0] not in already_done:
        results.append(line)    # if so, add this line the the results list
        already_done.add(line[0])

相关问题 更多 >