Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: Add unique values from a CSV column to list

I’m going through a CSV that has a list of cargo movements between various ports, and I’d like to take all the unique values for the ports into a new list.

Currently, I have the below, it adds every value under the ‘Origin Ports’ column, how can I make sure it adds just the unique values under that column? Thank you.

import csv

CSV_FILE = "Bitumen2021Exports.csv"

ports = []
  
with open(CSV_FILE, encoding="utf-8-sig") as bitumen_csv:
    bitumen_reader = csv.DictReader(bitumen_csv)
    for port in bitumen_reader:
        ports.append(port['ORIGIN PORT'])

print(ports)

The data in the CSV looks like below:
enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One way based on your code:

import csv

CSV_FILE = "Bitumen2021Exports.csv"

ports = []
  
with open(CSV_FILE, encoding="utf-8-sig") as bitumen_csv:
    bitumen_reader = csv.DictReader(bitumen_csv)
    for port in bitumen_reader:
        if port['ORIGIN PORTS'] not in ports:
              ports.append(port['ORIGIN PORTS'])

print(ports)

Another way is to import the csv into a pandas df and use column.unique().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading