这是对上一个问题的阐述,但是随着我对 python 的深入研究,我对 python 如何处理 csv 文件感到更加困惑。
我有一个 csv 文件,它必须保持这种状态(例如,不能将其转换为文本文件)。它相当于一个 5 行 x 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很陌生。
最佳答案
对于 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 处理程序。事实上,大多数东西都已经内置在标准库中了。
关于python - 如何使用带有完整标题的python导入csv文件,其中第一列是非数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3428532/