python - 如何在python中将数组附加到文本文件
问题描述
我正在尝试创建一个以多行作为标题的文件并附加一列数字。我在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 文件的屏幕截图。 这是我的结果的屏幕截图
解决方案
请注意,numpy.savetxt
如果您允许,它将为您附加一个标题字符串到文件中。例如:
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
。
推荐阅读
- python - Python IBM Watson Speech to Text API 将文本转换为 CSV
- github-api - GitHub OAuth2 令牌:如何限制读取私有仓库的访问权限
- c# - Selenium WebDriver 验证错误消息文本
- c - 您如何确定用于堆栈保护的金丝雀类型?
- angular - 为什么我的全局加载程序拦截器在 angular12 中无法正常工作?
- amazon-web-services - AWS 步骤函数 - 重用上一步的输出
- typescript - 从 TypeScript 类型检查中排除未导入的文件
- python-3.x - 无法从“pip._internal.index”pip3 导入名称“PackageFinder”
- javascript - 单击选项卡标题时显示和隐藏 div
- javascript - 试图在他/她的生日为成员赋予角色,然后在 24 小时后将其删除(Discord.js)