Extract csv file specific columns to list in Python Extract csv file specific columns to list in Python numpy numpy

Extract csv file specific columns to list in Python


This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandascolnames = ['year', 'name', 'city', 'latitude', 'longitude']data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()latitude = data.latitude.tolist()longitude = data.longitude.tolist()


A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv# open the file in universal line ending mode with open('test.csv', 'rU') as infile:  # read the file as a dictionary for each row ({header : value})  reader = csv.DictReader(infile)  data = {}  for row in reader:    for header, value in row.items():      try:        data[header].append(value)      except KeyError:        data[header] = [value]# extract the variables you wantnames = data['name']latitude = data['latitude']longitude = data['longitude']


import csvfrom sys import argvd = open("mydata.csv", "r")db = []for line in csv.reader(d):    db.append(line)# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.