Peter Jeppo
Peter Jeppo

Reputation: 57

CSV reader and random sample

I was trying to make a CSV reader function which I can't seem to work and I'm not sure how to fix it.

fileobj = open("...") # open file for reading as usual
reader = csv.reader(fileobj)
for row in reader:
    # process the row
    first_column = row[0]     
    second_column = row[1]
    third_column = row[2]
fileobj.close()

print(random.sample(first_column, 2))

I understand that first_column is only giving me the bottom value of that column and therefore not allowing me to print a random sample. I'm not sure how to fix this.

Any help is greatly appreciated

Upvotes: 0

Views: 119

Answers (1)

user2390182
user2390182

Reputation: 73470

You can do this using a typical transpositioning pattern zip(*...):

with open("...") as fileobj: # open file with context manager as recommended ;)
    reader = csv.reader(fileobj)
    rows = list(reader)  # if you need the rows as well
    columns = list(zip(*rows)) # you can just use the fresh reader here as well
    # columns = zip(*rows)  # suffices in Python2
print(random.sample(columns[0], 2))

See the docs on zip and argument unpacking.

Upvotes: 2

Related Questions