【发布时间】:2017-03-20 16:38:26
【问题描述】:
我已经在 Python 上工作了大约 2 个月,所以我对它的理解还不错。
我的目标是使用 CSV 数据创建一个矩阵,然后从该 CSV 文件第 3 列中的数据填充该矩阵。
到目前为止,我想出了这个代码:
import csv
import csv
def readcsv(csvfile_name):
with open(csvfile_name) as csvfile:
file=csv.reader(csvfile, delimiter=",")
#remove rubbish data in first few rows
skiprows = int(input('Number of rows to skip? '))
for i in range(skiprows):
_ = next(file)
#change strings into integers/floats
for z in file:
z[:2]=map(int, z[:2])
z[2:]=map(float, z[2:])
print(z[:2])
return
用上面的代码去掉垃圾数据后,CSV文件中的数据是这样的:
Input:
1 1 51 9 3
1 2 39 4 4
1 3 40 3 9
1 4 60 2 .
1 5 80 2 .
2 1 40 6 .
2 2 28 4 .
2 3 40 2 .
2 4 39 3 .
3 1 10 . .
3 2 20 . .
3 3 30 . .
3 4 40 . .
. . . . .
输出应如下所示:
1 2 3 4 . .
1 51 39 40 60
2 40 28 40 39
3 10 20 30 40
.
.
这个 CSV 文件中大约有几千行和几千列,但我只对 CSV 文件的前 3 列感兴趣。所以第一列和第二列基本上就像矩阵的坐标,然后用第三列的数据填充矩阵。
经过大量试验和错误,我意识到 numpy 是使用矩阵的方法。这是我迄今为止使用示例数据尝试过的:
left_column = [1, 2, 1, 2, 1, 2, 1, 2]
middle_column = [1, 1, 3, 3, 2, 2, 4, 4]
right_column = [1., 5., 3., 7., 2., 6., 4., 8.]
import numpy as np
m = np.zeros((max(left_column), max(middle_column)), dtype=np.float)
for x, y, z in zip(left_column, middle_column, right_column):
x -= 1 # Because the indicies are 1-based
y -= 1 # Need to be 0-based
m[x, y] = z
print(m)
#: array([[ 1., 2., 3., 4.],
#: [ 5., 6., 7., 8.]])
但是,在我的脚本中指定所有数据来生成矩阵对我来说是不现实的。我尝试使用生成器从我的 CSV 文件中提取数据,但对我来说效果不佳。
我尽可能多地学习了 numpy,但它似乎要求我的数据已经是矩阵形式,但事实并非如此。
【问题讨论】:
-
我不明白最后两列的意思。前三个是明确的...(行、列、值)
标签: python csv parsing numpy matrix