【发布时间】:2017-06-12 02:31:30
【问题描述】:
我有一个文件,内容为
18
21
24
27
30
还有数组
[[ 1 6 11]
[ 2 7 12]
[ 3 8 13]
[ 4 9 14]
[ 5 10 15]]
如何将此数组写入文件,以便每一行都与适当的行相对应,例如:
18 1 6 11
21 2 7 12
24 3 8 13
27 4 9 14
30 5 10 15
我已经使用了这段代码,但它并没有按照我的意愿编写代码。代码:
import numpy as np
ourlist = []
for i in range(1, 16):
ourlist.append(i)
mydata = np.matrix([ourlist])
array_from_list=(mydata.reshape(3, 5))
x_transpose = (np.transpose(array_from_list)) # the array above
with open('5rows.txt','a') as f: #the file containing numbers
for elements in x_transpose:
f.write(str(elements))
f.write('\n')
它改为将元素写入行尾。如果可能的话,你能告诉我我该怎么做吗?非常感谢您的帮助!
【问题讨论】:
-
您是否尝试过使用数据框?它可能会让你的事情变得更容易。
-
所以文件中的第一列是行的总和。这不是你放的吗?我的回答假设需要一个水平追加,但也许你是先写总和,然后尝试在它旁边写矩阵。这不是解决问题的好方法。也许我太自以为是了,但我想我应该对你未来的利益感到好奇。
标签: python file numpy string-formatting