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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37686105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:48:12  来源:igfitidea点击:

Python - splitting data as columns in csv file

pythoncsvmatplotlib

提问by iron2man

I have data in a csv file that looks like that is imported as this.

我在一个 csv 文件中有数据,看起来像这样导入。

import csv

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

the data will come out as this to where it prints out the rows like data[0] = ['10', '2', '2']and so on.

数据将作为这个输出到它打印出诸如此类的行的地方data[0] = ['10', '2', '2']

What i'm wanting though is to retrieve the data as columns in instead of rows, to where in this case, there are 3 columns.

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

回答by Alexander

You can create three separate lists, and then append to each using csv.reader.

您可以创建三个单独的列表,然后使用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])

回答by jpmc26

A little more automatic and flexible version of 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)

You could also modify this to use column headers instead of column numbers.

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

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)

回答by Ryan James

Another option, if you have numpyinstalled, you can use loadtxtto read a csv file into a numpy array. You can then transpose the array if you want more columns than rows (I wasn't quite clear on how you wanted the data to look). For example:

另一种选择,如果您已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)