Python - 将数据拆分为csv文件中的列

时间:2016-06-07 17:52:48

标签: python csv matplotlib

我在csv文件中有数据,看起来就是这样导入的。

import csv

with open('Half-life.csv', 'r') as f:
    data = list(csv.reader(f))

数据将在此处显示为打印出data[0] = ['10', '2', '2']等行的位置。

我想要的是将数据检索为列而不是行,在这种情况下,有3列。

3 个答案:

答案 0 :(得分:3)

Alexander's answer的更自动,更灵活的版本:

import csv
from collections import defaultdict

columns = defaultdict(list)
with open('Half-life.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        for i in range(len(row)):
            columns[i].append(row[i])
# Following line is only necessary if you want a key error for invalid column numbers
columns = dict(columns)

您也可以修改它以使用列标题而不是列号。

import csv
from collections import defaultdict

columns = defaultdict(list)
with open('Half-life.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    headers = next(reader)
    column_nums = range(len(headers)) # Do NOT change to xrange
    for row in reader:
        for i in column_nums:
            columns[headers[i]].append(row[i])
# Following line is only necessary if you want a key error for invalid column names
columns = dict(columns)

答案 1 :(得分:2)

您可以创建三个单独的列表,然后使用csv.reader附加到每个列表。

import csv

c1 = []
c2 = []
c3 = []
with open('Half-life.csv', 'r') as f:
    reader = csv.reader(f, delimiter=',')
    for row in reader:
        c1.append(row[0])
        c2.append(row[1])
        c3.append(row[2])

答案 2 :(得分:2)

另一个选项是,如果安装了numpy,则可以使用loadtxt将csv文件读入numpy数组。如果你想要更多的列而不是行,你可以转置数组(我不清楚你想要数据的外观)。例如:

import numpy as np
# Load data
data = np.loadtxt('csv_file.csv', delimiter=',')
# Transpose data if needs be
data = np.transpose(data)