python中CSV文件的所有列的唯一元素,而无需使用pandas
我正在尝试获取CSV中所有列的唯一值。我正在获取所有列的列号并创建集合,并尝试浏览CSV数据并找到唯一的列。但是第二个循环仅执行一次。
decoded_file = data_file.read().decode('utf-8')
reader = csv.reader(decoded_file.splitlines(),
delimiter=',')
list_reader = list(reader)
data = iter(list_reader)
next(data) #skipping the header
col_number = len(next(data))
col_sets = [set() for i in range(col_number)]
for col in range(col_number):
for new_row in data:
col_sets[col].add(new_row[col])
print(col_sets[col])
我需要为每列获取所有唯一值,并将其添加到col_sets以访问它。最好的方法是什么?
I am trying to get the unique values of all the columns in the CSV. I am getting the column number and creating sets for all the columns and trying to go through the csv data and find the unique columns. But the second loop executes only once.
decoded_file = data_file.read().decode('utf-8')
reader = csv.reader(decoded_file.splitlines(),
delimiter=',')
list_reader = list(reader)
data = iter(list_reader)
next(data) #skipping the header
col_number = len(next(data))
col_sets = [set() for i in range(col_number)]
for col in range(col_number):
for new_row in data:
col_sets[col].add(new_row[col])
print(col_sets[col])
I need to get all the unique values for each column and add it to col_sets to access it. What is the best way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一切都很好,但是您应该只更改迭代顺序。
Everything is good, but you should just change the order of iterations.