将CSV行转换为python中的列

时间:2019-01-29 18:44:00

标签: python csv

我有CSV文件,例如: CSV DATA

想要转换为单个列表,例如: 253,514,517,6514,6518,407,865

忽略0和重复项时按行读取数据

3 个答案:

答案 0 :(得分:1)

'table.csv'为您的csv文件。你可以做类似的事情

import csv

with open('table.csv') as table:
    reader = csv.reader(table)
    header = next(reader)  # discard header
    numbers = set(int(num) for row in reader for num in row if int(num))

print(numbers)

然后,您的号码将存储在numbers中。但是请注意,该解决方案仅在顺序不重要的情况下有效。

使用以下csv文件尝试一下:

a, b, c
1, 2, 0
7, -1, 3
0, 7, 0

输出为{1, 2, 3, 7, -1}

答案 1 :(得分:0)

import csv
import itertools
from collections import OrderedDict

with open('data.csv') as f:
    reader = csv.reader(f)
    next(reader)  # ignore header
    nums = list(OrderedDict.fromkeys(  # remove duplicates while keeping order
        filter(  # remove 0s
            None,
            map(
                int,
                itertools.chain.from_iterable(reader)  # flatten
            )
        )
    ))

答案 2 :(得分:0)

也许这可以解决您的问题

new_file = open('single.csv', 'a', encoding="utf-8")
values = ''
with open('file.csv', 'r') as csvfile:
    for value in csvfile:
        value = value.replace("0,", "").replace('\n', '').replace(",,", ",")
        values += str(value)+","

    new_file.write(values[:-1])