1

我是 python 新手,需要一些关于以下方面的建议。我有一个包含多个字段的文件,示例如下

# with duplicates
name1 14019 3 0.5564 0.0929 0.6494
name1 14022 0 0.5557 0.0990 0.6547
name1 14016 0 0.5511 0.0984 0.6495
name2 11 8 0.5119 0.0938 0.6057
name2 12 18 0.5331 0.0876 0.6206
name3 16 20 0.5172 0.0875 0.6047
name3 17 29 0.5441 0.0657 0.6098
# without duplicates
name1 14022 0 0.5557 0.0990 0.6547
name2 12 18 0.5331 0.0876 0.6206
name3 17 29 0.5441 0.0657 0.6098

首先是名称,其他字段是数字(来自预测)。预测有重复的名称,但预测不同。我的任务是根据最后一个字段的比较来删除重复项。应采用最后一列中具有 MAXIMUM 的行。

我正在比较重复条目的最后一个字段的步骤。我应该使用 lambda 还是可以直接过滤?列表是否正确使用,或者可以在从文件中逐行读取时在流程中执行此操作?

您对我们的帮助不胜感激!

import csv

fi = open("filein.txt", "rb")
fo = open("fileout.txt", "wb")

reader = csv.reader(fi,delimiter=' ')
writer = csv.writer(fo,delimiter=' ')

names = set()
datum = []
datum2 = []

for row in reader:
  if row[0] not in names:
    names.add(row[0])
    row_new1 = [row[0],row[3],row[4],row[5]]
    datum.append(row_new)
    writer1.writerow(row_new1)
  else:
    row_new2 = [row[0],row[3],row[4],row[5]]
    datum2.append(row_new2)
    writer2.writerow(row_new2)
4

3 回答 3

1

下面的代码可能有一些用处,我是用字典做的:

import csv

fi = open("filein.txt", "rb")
reader = csv.reader(fi,delimiter=' ')

dict = {}
for row in reader:
    if row[0] in dict:
        if float(dict[row[0]][-1]) < float(row[-1]):
            dict[row[0]] = row[1:]
    else:
        dict[row[0]] = row[1:]
print dict

这输出:

{'name2': ['12', '18', '0.5331', '0.0876', '0.6206'], 'name3': ['17', '29', '0.5441', '0.0657', '0.6098'], 'name1': ['14022', '0', '0.5557', '0.0990', '0.6547']}
于 2013-06-14T09:42:06.617 回答
0

itertools 是你的朋友:

import csv
import itertools
import operator

fi = open("filein.txt", "rb")
fo = open("fileout.txt", "wb")

reader = csv.reader(fi,delimiter=' ',)
writer = csv.writer(fo,delimiter=' ')


# unpack datas in generator
duplicated_datas = ( tuple(row)  for row in reader )


# groupby name
groups = itertools.groupby(duplicated_datas,key=operator.itemgetter(0))


for k,v in groups:

    # sort by 5-th value
    val = [values for values in v]
    val.sort( key= lambda x: float(x[5]), reverse=True )

    #output
    writer.writerow( ",".join( [ i for i in val[0] ] ) )
于 2013-06-14T09:58:50.367 回答
0

我希望我已经很好地理解了你的问题。Pandas是一个非常有效的库,您也可以将其用于诸如此类的简单任务。

import pandas as pd
data = pd.read_csv('dataset.csv') # filein.txt in your case
length = len(data['names'].unique())
res = pd.DataFrame(columns=('names', 'field1', 'field2','field3','field4','field5'))
for i in range(0,length):
    name_filter = data[data['names'] == data['names'].unique()[i]] #filters the entire dataset based on the unique items in the 'names' field
    field5_max_filter = name_filter[name_filter['field5'] == name_filter['field5'].max() ] # filters the name based on the max value from 'field5'
    res = res.append(field5_max_filter, ignore_index=True) # appends output to new dataframe
    i=i+1
    res.to_csv('newdata.csv') # writes output to csv
于 2013-06-14T10:06:00.133 回答