Print a column of a csv


I have a csv file several columns. I simplify it in the following case with two.

ID     texto
1      Los niños comen sardinas
2      Los pájaros vuelan alto porque tienen alas
3      Érase una vez la vida
4      Un 67% de los adultos vive en la pobreza

I want to print only the "text" column. And I do not get it. I have tried a thousand ways:

import pandas as pd
fields = ['ID', 'texto']

df = pd.read_csv('Libro1.csv', usecols=fields)
# See the keys
print (df.keys())
# See content in 'ID' y 'texto'
print (df.texto)


raise ValueError("Usecols do not match names.")
ValueError: Usecols do not match names.


import csv
from collections import defaultdict

columns = defaultdict(list) # each value in each column is appended to a list

with open('Libro1.csv') as csvfile:
    reader = csv.DictReader(csvfile) # read rows into a dictionary format
    for row in reader: # read a row as {column1: value1, column2: value2,...}
        for (k,v) in row.items(): # go over each column name and value
            columns[k].append(v) # append the value into the appropriate list
                                 # based on column name k


None of this methods extracts me

asked by pyring 03.11.2017 в 17:53

1 answer


Starting from that you have a csv like the following:


ID; text
  1; Children eat sardines
  2; Birds fly high because they have wings
  3; Once upon a time, life
  4; 67% of adults live in poverty

You must indicate the separator properly:

import pandas as pd

fields = ['ID', 'texto']
df = pd.read_csv('Libro1.csv', usecols=fields,  sep=';')

Or with the csv module:

with open('Libro1.csv') as csvfile:
    reader = csv.DictReader(csvfile,  delimiter = ";")
    for row in reader:
        print (row["texto"]
answered by 03.11.2017 / 18:20