对于index.csv
文件,其第四列有十个数字,范围从1
- 5
。每个数字都可以视为一个索引,并且每个索引都对应于中的数字数组filename.csv
。
的行号filename.csv
表示索引,每行有三个数字。我的问题是关于使用嵌套循环将数字传输filename.csv
到中index.csv
。
from numpy import genfromtxt
import numpy as np
import csv
import collections
data1 = genfromtxt('filename.csv', delimiter=',')
data2 = genfromtxt('index.csv', delimiter=',')
out = np.zeros((len(data2),len(data1)))
for row in data2:
for ch_row in range(len(data1)):
if (row[3] == ch_row + 1):
out = row.tolist() + data1[ch_row].tolist()
print(out)
writer = csv.writer(open('dn.csv','w'), delimiter=',',quoting=csv.QUOTE_ALL)
writer.writerow(out)
例如,index.csv
contains1,2,5,3,4,1,4,5,2,3
和的第四列filename.csv
:
# filename.csv
20 30 50
70 60 45
35 26 77
93 37 68
13 08 55
我需要的是从写索引行filename.csv
至index.csv
并存储在第5,第6和第7列数这些:
# index.csv
# 4 5 6 7
... 1 20 30 50
... 2 70 60 45
... 5 13 08 55
... 3 35 26 77
... 4 93 37 68
... 1 20 30 50
... 4 93 37 68
... 5 13 08 55
... 2 70 60 45
... 3 35 26 77
如果我执行“ print(out)”,它会给出正确的答案。但是,当我在外壳程序中输入“ out”时,只有一行显示为[1.0,1.0,1.0,1.0,20.0,30.0,50.0]
我需要将所有值存储在“输出”变量中,并将它们写入dn.csv文件。
这应该为您解决问题:
代码:
from csv import reader, writer
data = list(reader(open("filename.csv", "r"), delimiter=" "))
out = writer(open("output.csv", "w"), delimiter=" ")
for row in reader(open("index.csv", "r"), delimiter=" "):
out.writerow(row + data[int(row[3])])
index.csv:
0 0 0 1
0 0 0 2
0 0 0 3
filename.csv:
20 30 50
70 60 45
35 26 77
93 37 68
13 08 55
产生输出:
0 0 0 1 70 60 45
0 0 0 2 35 26 77
0 0 0 3 93 37 68
注意:这里不需要使用numpy。标准库csv
模块将为您完成大部分工作。
我还必须对样本数据集进行一些修改,因为您显示的样本中的索引超出了样本数据的范围filename.csv
。
另请注意,Python(与大多数语言一样)使用第0个索引。因此,您可能不得不摆弄上面的代码以完全满足您的需求。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句