如何将数组附加到 python 中的文本文件
How to append an array to a text file in python
我正在尝试创建一个包含多行的文件 header 并附加一列数字。我在 header 之后附加 numpy.matrix
时遇到一些问题。我写了一段代码如下
import numpy as np
import pandas as pd
import xlrd
df = pd.read_csv('Region_SGeMS.csv', header=None)
matrix = np.asmatrix(df)
#print(matrix)
s = np.shape(matrix)
print(s)
row = s[0]
col = s[1]
a = np.flip(matrix, 0)
b = np.reshape(a, (400, 1))
print(b)
f = open('Region.txt', 'w')
f.write(str(s[0]))
f.write(' ')
f.write(str(s[1]))
f.write(' 1 \n')
f.write('1 \n')
f.write('facies \n')
with open('Region.txt', 'a+') as outfile:
np.savetxt(outfile,b)
但是,突出显示的数字应该是 2,而不是 0。我还附上了原始 excel 文件的屏幕截图。 Here is a screenshot of my result
f = open('Region.txt', 'w')
f.write('first line \n')
f.write('second line \n')
f.close()
with open('Region.txt', 'a+') as outfile:
np.savetxt(outfile,np.random.rand(10,3))
请注意,如果您愿意,numpy.savetxt
将为您在文件中附加一个 header 字符串。例如:
import numpy as np
# Recreate the original csv data
one_block = np.ones((10,10))
A = np.block([ [0*one_block,one_block],[2*one_block,3*one_block] ])
M,N = A.shape
# Recreate b
a = np.flip(A,0)
b = a.reshape(400,1)
hdr_str = """{M:d} {N:d} 1
1
facies""".format(M=M,N=N)
outfile = 'Region.txt'
np.savetxt(outfile,b,header=hdr_str,comments='')
下面是我尝试重现您的问题的屏幕截图。没有虚假的 0
.
我正在尝试创建一个包含多行的文件 header 并附加一列数字。我在 header 之后附加 numpy.matrix
时遇到一些问题。我写了一段代码如下
import numpy as np
import pandas as pd
import xlrd
df = pd.read_csv('Region_SGeMS.csv', header=None)
matrix = np.asmatrix(df)
#print(matrix)
s = np.shape(matrix)
print(s)
row = s[0]
col = s[1]
a = np.flip(matrix, 0)
b = np.reshape(a, (400, 1))
print(b)
f = open('Region.txt', 'w')
f.write(str(s[0]))
f.write(' ')
f.write(str(s[1]))
f.write(' 1 \n')
f.write('1 \n')
f.write('facies \n')
with open('Region.txt', 'a+') as outfile:
np.savetxt(outfile,b)
但是,突出显示的数字应该是 2,而不是 0。我还附上了原始 excel 文件的屏幕截图。 Here is a screenshot of my result
f = open('Region.txt', 'w')
f.write('first line \n')
f.write('second line \n')
f.close()
with open('Region.txt', 'a+') as outfile:
np.savetxt(outfile,np.random.rand(10,3))
请注意,如果您愿意,numpy.savetxt
将为您在文件中附加一个 header 字符串。例如:
import numpy as np
# Recreate the original csv data
one_block = np.ones((10,10))
A = np.block([ [0*one_block,one_block],[2*one_block,3*one_block] ])
M,N = A.shape
# Recreate b
a = np.flip(A,0)
b = a.reshape(400,1)
hdr_str = """{M:d} {N:d} 1
1
facies""".format(M=M,N=N)
outfile = 'Region.txt'
np.savetxt(outfile,b,header=hdr_str,comments='')
下面是我尝试重现您的问题的屏幕截图。没有虚假的 0
.