CSV阅读器和随机样本

时间:2017-10-15 09:13:09

标签: python csv

我试图制作一个我无法工作的CSV阅读器功能,而且我不确定如何修复它。

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))

据我所知first_column只给出了该列的最低值,因此不允许我打印随机样本。我不知道如何解决这个问题。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:2)

您可以使用典型的转置模式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))

请参阅zipargument unpacking上的文档。