如何使用Python导入保留表头的CSV文件,且第一列为非数值类型

91 投票
4 回答
334020 浏览
提问于 2025-04-16 02:27

这是对之前一个问题的详细说明,但随着我对Python的深入学习,我对Python如何处理CSV文件的理解变得更加困惑。

我有一个CSV文件,它必须保持这种格式(例如,不能转换成文本文件)。这个文件就像一个5行11列的数组、矩阵或向量。

我一直在尝试使用我在这里和其他地方(例如python.org)找到的各种方法来读取这个CSV文件,以便保持列和行之间的关系,其中第一行和第一列是非数字的值。其余的都是浮点数,包含正数和负数的混合。

我想做的是导入这个CSV文件,并在Python中编译它,这样如果我引用一个列标题,就能返回与之相关的存储在行中的值。例如:

>>> workers, constant, age
>>> workers
    w0
    w1
    w2
    w3
    constant
    7.334
    5.235
    3.225
    0
    age
    -1.406
    -4.936
    -1.478
    0

等等……

我在寻找处理这种数据结构的技巧。我对Python非常陌生。

4 个回答

15

你可以使用pandas这个库,然后像这样引用行和列:

import pandas as pd

input = pd.read_csv("path_to_file");

#for accessing ith row:
input.iloc[i]

#for accessing column named X
input.X

#for accessing ith row and column named X
input.iloc[i].X
166

对于Python 3

去掉 rb 这个参数,改用 r,或者直接不传参数(这样会使用默认的读取模式)。

with open( <path-to-file>, 'r' ) as theFile:
    reader = csv.DictReader(theFile)
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'
        print(line)

对于Python 2

import csv
with open( <path-to-file>, "rb" ) as theFile:
    reader = csv.DictReader( theFile )
    for line in reader:
        # line is { 'workers': 'w0', 'constant': 7.334, 'age': -1.406, ... }
        # e.g. print( line[ 'workers' ] ) yields 'w0'

Python有一个强大的内置CSV处理工具。实际上,大部分功能都已经包含在标准库里了。

124

Python的csv模块是按行处理数据的,这也是查看数据的常见方式。不过你似乎想要按列来处理数据。这里有一种方法可以做到这一点。

假设你的文件叫做 myclone.csv,里面的内容是

workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0

这段代码应该能给你一些启发:

>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
...    column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
...   for h, v in zip(headers, row):
...     column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>

为了把你的数字值转换成浮点数,可以在前面加上这个

converters = [str.strip] + [float] * (len(headers) - 1)

然后对每一行做这个操作,而不是像上面那两行那样。

for h, v, conv in zip(headers, row, converters):
  column[h].append(conv(v))

撰写回答