我已经在Python上工作了大约2个月,所以我对它有了一个很好的理解。从CSV文件创建矩阵
我的目标是使用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,但它看起来好像它需要我的数据已经是矩阵形式,事实并非如此。
我不明白最后两列的意思。前三个是清楚的...(行,列,值) – Nikaidoh