如何使用python导入一个csv文件,其中头一列是非数字的

2024-04-25 07:51:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这是前一个问题的详细说明,但是随着我深入研究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很陌生。


Tags: 文件csv方法orgage状态地方矩阵
3条回答

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))

而不是上面类似的两行。

可以使用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

对于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处理程序。事实上,大多数东西已经内置到标准库中。

对于Python 3

删除rb参数并使用r或不传递参数(default read mode)。

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)

相关问题 更多 >