Grab specific column csv with python

Asked

Viewed 3,618 times

0

I have a method that opens a CSV file but would like to go straight into a specific column, I tried to do it this way list2 = [row.split()[3] for row in f], but returns a piece of the file and not the column. Is it possible to do this without using PANDAS? My method:

import csv
list2 = []
count = 0

with open('meuarquivo.csv') as f:
    list2 = [row.split()[3] for row in f]

while(count <= 20):
    print(list2[count])
    count+=1
  • Are the columns separated by a comma? If so, use row.split(','). split no parameters separated by spaces.

2 answers

2


Yes, it is possible to read a specific column without using external libraries such as pandas, your code does not work because you did not specify which column separator is on split. I created a variable for the tab if you are using another, just change.

''' Conteudo CSV
nome,idade
Laerte,23
Maria,18
'''

separador = ','

with open('teste.csv', 'r') as txt_file:
    for line_number, content in enumerate(txt_file):
        if line_number:  # pula cabeçalho
            colunas = content.strip().split(separador)
            print(f"Nome: {colunas[0]}, \nIdade: {colunas[1]}")

if is to check if it is not a header row but a row containing the data.

1

Just use the module itself csv imported in your example, using the DictReader, for example:

def get_column_of_csv(filename, column):
  with open(filename) as stream:
    reader = csv.DictReader(stream)
    for row in reader:
      yield row[column]

Thus, for a CSV:

seq,firstname,lastname,age
1,Helen,King,58
2,Emilie,Joseph,59
3,Bess,Frazier,29
4,Amy,Gross,33
5,Olga,Sutton,62
6,Gary,Moreno,54
7,Myrtie,Freeman,47
8,Philip,Adkins,32
9,Thomas,Morales,64
10,Stella,Rodgers,43

We could do

for name in get_column_of_csv('data.csv', 'firstname'):
  print(name)

Getting the result

Helen
Emilie
Bess
Amy
Olga
Gary
Myrtie
Philip
Thomas
Stella

It is worth commenting that, by default, the class DictReader will consider the first row of the CSV file as the column name, so it was possible to identify the column firstname in the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.