一、问题:从这个 https://blog.csdn.net/qq_42052864/article/details/81591511 中获得的灵感,但是我是要实现存储为2行n列的?怎么办呢?
import numpy as np wab1 = [1,2,3,4,5,6,7] wab2 = [7,6,5,4,3,2,1] np.savetxt('new.csv',wab2, delimiter = ',')
#结果:new.csv 7.00E+00 6.00E+00 5.00E+00 4.00E+00 3.00E+00 2.00E+00 1.00E+00
解决方法1:那我在存储一次不就行了?
import numpy as np wab1 = [1,2,3,4,5,6,7] wab2 = [7,6,5,4,3,2,1] np.savetxt('new.csv',wab1, delimiter = ',')
#结果:new.csv 1.00E+00 2.00E+00 3.00E+00 4.00E+00 5.00E+00 6.00E+00 7.00E+00 #被覆盖了,哈哈,以失败告终
解决方法2:np.array(my_matrix).reshape(7,2)
到后面才发现这个np.array是将将每个元素按顺序拿出来,然后重新行排列为想要的m*n
那么我们将两个列表交叉插入后就可以存储了,试试吧!
import numpy as np wab1 = [1,2,3,4,5,6,7] wab2 = [7,6,5,4,3,2,1] list2 = [] for (i,j) in zip(wab1,wab2): list2.append(i) list2.append(j) print(list2) a = np.array(list2).reshape(7,2) print(a) np.savetxt('new.csv',a, delimiter = ',')
#output [1, 7, 2, 6, 3, 5, 4, 4, 5, 3, 6, 2, 7, 1] [[1 7] [2 6] [3 5] [4 4] [5 3] [6 2] [7 1]] #new.csv 1.00E+00 7.00E+00 2.00E+00 6.00E+00 3.00E+00 5.00E+00 4.00E+00 4.00E+00 5.00E+00 3.00E+00 6.00E+00 2.00E+00 7.00E+00 1.00E+00
这样就可以了啊!嘻嘻!
中途遇到的小问题:
import numpy as np wab1 = [1,2,3,4,5,6,7] wab2 = [7,6,5,4,3,2,1] #转换成列 Wab1 = np.array(wab1).reshape(-1,1) Wab2 = np.array(wab2).reshape(-1,1) my_matrix = [Wab1,Wab2] #这是一个矩阵7*1*2,不是 7*2 的
二。提取数据:
csv文件是这么操作的:
b = np.loadtxt(open("new.csv","rb"),delimiter=",",skiprows=0) print(b)
#结果: [[1. 7.] [2. 6.] [3. 5.] [4. 4.] [5. 3.] [6. 2.] [7. 1.]]
txt文件如下:
np.savetxt('new.txt',a, delimiter = ',') c = np.loadtxt('new.txt',delimiter=",") print(c)
#结果: [[1. 7.] [2. 6.] [3. 5.] [4. 4.] [5. 3.] [6. 2.] [7. 1.]] #new.txt 1.000000000000000000e+00,7.000000000000000000e+00 2.000000000000000000e+00,6.000000000000000000e+00 3.000000000000000000e+00,5.000000000000000000e+00 4.000000000000000000e+00,4.000000000000000000e+00 5.000000000000000000e+00,3.000000000000000000e+00 6.000000000000000000e+00,2.000000000000000000e+00 7.000000000000000000e+00,1.000000000000000000e+00
三、如果遇到这个(请把csv文件关闭):
Traceback (most recent call last): File "C:UsersAdministratorDesktop矩阵导入csv导入数据-实验import-data-exp.py", line 13, in <module> np.savetxt('new.csv',a, delimiter = ',') File "C:UsersAdministratorAppDataLocalProgramsPythonPython37-32libsite-packages umpylib pyio.py", line 1359, in savetxt open(fname, 'wt').close() PermissionError: [Errno 13] Permission denied: 'new.csv'