2017-09-28 1 views
0

가장 오래된을 제거하지만 제목은파이썬은 CSV에 복제하고 난 항목의 이러한 종류 csv 파일을

abcd,123,2017-09-27 17:38:38 
cdfg,324,2017-09-27 18:38:38 
abcd,123,2017-09-27 19:38:38 
cdfg,423,2017-09-27 16:38:38 

내가 첫 번째 열에서 중복을 찾으려하지 않고 그것을 기반으로 오래된 항목을 제거해야 찾을 datetime 형식의 세 번째 열은 무엇입니까?

결과는 다음과 같아야합니다

abcd,123,2017-09-27 19:38:38 
cdfg,423,2017-09-27 16:38:38 

어떤 아이디어?

+0

사용'pandas'을 ... –

+0

당신은 핵심 파이썬에서 원하는? –

답변

1

표준 라이브러리의 일부인 csv 모듈을 사용하여, 당신이 할 수 있습니다 :

import csv 
from collections import OrderedDict 
# you can use a normal dict if the order of the rows does not matter 

with open('file.csv') as f: 
    r = csv.reader(f) 
    d = OrderedDict() 
    for row in r: 
    if row[0] not in d or d[row[0]][2] < row[2]: 
     d[row[0]] = row 
d.values() 
# [['cdfg', '324', '2017-09-27 18:38:38'], ['abcd', '123', '2017-09-27 19:38:38']] 

with open('file_out.csv', 'w') as f: 
    w = csv.writer(f) 
    w.writerows(d.values()) 
0

awk에 하나 있습니다. HTH는 Python 버전을 기다리는 동안.

$ awk -F\, ' 
{ 
    if(($1 in a==0) || a[$1]<$3) { 
     a[$1]=$3 
     b[$1]=$0 
    } 
} 
END { 
    for(i in b) 
     print b[i] 
}' file 
cdfg,324,2017-09-27 18:38:38 
abcd,123,2017-09-27 19:38:38 
관련 문제