Подтвердить что ты не робот

Удаление повторяющихся строк из файла csv с помощью python script

Цель

Я загрузил CSV файл из hotmail, но в нем много дубликатов. Эти дубликаты являются полными копиями, и я не знаю, почему мой телефон создал их.

Я хочу избавиться от дубликатов.

Подход

Запишите python script, чтобы удалить дубликаты.

Техническая спецификация

Windows XP SP 3
Python 2.7
CSV file with 400 contacts

4b9b3361

Ответ 1

ОБНОВЛЕНИЕ: 2016

Если вы счастливы использовать полезную more_itertools внешнюю библиотеку:

from more_itertools import unique_everseen
with open('1.csv','r') as f, open('2.csv','w') as out_file:
    out_file.writelines(unique_everseen(f))

Более эффективная версия решения @IcyFlame

with open('1.csv','r') as in_file, open('2.csv','w') as out_file:
    seen = set() # set for fast O(1) amortized lookup
    for line in in_file:
        if line in seen: continue # skip duplicate

        seen.add(line)
        out_file.write(line)

Чтобы отредактировать один и тот же файл на месте, вы можете использовать этот

import fileinput
seen = set() # set for fast O(1) amortized lookup
for line in fileinput.FileInput('1.csv', inplace=1):
    if line in seen: continue # skip duplicate

    seen.add(line)
    print line, # standard output is now redirected to the file

Ответ 2

Вы можете эффективно добиться дедупликации с помощью Pandas:

import pandas as pd
file_name = "my_file_with_dupes.csv"
file_name_output = "my_file_without_dupes.csv"

df = pd.read_csv(file_name, sep="\t or ,")

# Notes:
# - the 'subset=None' means that every column is used 
#    to determine if two rows are different; to change that specify
#    the columns as an array
# - the 'inplace=True' means that the data structure is changed and
#   the duplicate rows are gone  
df.drop_duplicates(subset=None, inplace=True)

# Write the results to a different file
df.to_csv(file_name_output)

Ответ 3

Вы можете использовать следующие script:

предварительное условие:

  • 1.csv - это файл, состоящий из дубликатов
  • 2.csv - это выходной файл, который будет лишен дубликатов после выполнения этого script.

код



inFile = open('1.csv','r')

outFile = open('2.csv','w')

listLines = []

for line in inFile:

    if line in listLines:
        continue

    else:
        outFile.write(line)
        listLines.append(line)

outFile.close()

inFile.close()

Algorithm Explanation

Here, what I am doing is:

  1. opening a file in the read mode. This is the file that has the duplicates.
  2. Then in a loop that runs till the file is over, we check if the line has already encountered.
  3. If it has been encountered than we don't write it to the output file.
  4. If not we will write it to the output file and add it to the list of records that have been encountered already

Ответ 4

Более эффективная версия решения @jamylak: (с одной меньшей инструкцией)

with open('1.csv','r') as in_file, open('2.csv','w') as out_file:
    seen = set() # set for fast O(1) amortized lookup
    for line in in_file:
        if line not in seen: 
            seen.add(line)
            out_file.write(line)

Чтобы отредактировать один и тот же файл на месте, вы можете использовать этот

import fileinput
seen = set() # set for fast O(1) amortized lookup
for line in fileinput.FileInput('1.csv', inplace=1):
    if line not in seen:
        seen.add(line)
        print line, # standard output is now redirected to the file   

Ответ 5

Вы можете использовать библиотеку панд в блокноте jupyter или соответствующей IDE, я импортирую панды в блокнот jupyter и читаю файл csv

Затем сортируйте значения, соответственно, по каким параметрам присутствуют дубликаты, так как я определил два атрибута: сначала он будет отсортирован по времени, а затем по широте

.Затем удалите дубликаты, которые присутствуют в столбце времени или в столбце, относящемся к вам

Затем я сохраняю удаленные и отсортированные дубликаты как gps_sorted

import pandas as pd
stock=pd.read_csv("C:/Users/Donuts/GPS Trajectory/go_track_trackspoints.csv")
stock2=stock.sort_values(["time","latitude"],ascending=True)
stock2.drop_duplicates(subset=['time'])
stock2.to_csv("C:/Users/Donuts/gps_sorted.csv",)

Надеюсь, это поможет