我想设置写入文本文件的numpy数组的每个元素的字符长度
我目前得到的输出是:
99941 1 56765 56767 51785 51793 0 0 0 0
101150 1 59006 59005 51782 51783 0 0 0 0
正如您在上面的例子中看到的那样,随着数字的增加,列发生了移动。
但在理想情况下,输出应该如下所示:
99941 1 56765 56767 51785 51793 0 0 0 0
101150 1 59006 59005 51782 51783 0 0 0 0
有什么方法可以固定 numpy 数组的每个元素的字符长度,以便它在考虑元素字符长度后从右向左写入元素并保持列格式固定?
这是我正在处理的代码片段。
def calculate(self, ElementNum1, ElementNum2):
Angle = Function().Transformation(ElementNum1, ElementNum2)
ElementInfo = Shell().getElement(ElementNum2)
Card1 = np.array([0,0,0,0,0,0,0,0,0,0])
Card1.itemset(0,(ElementInfo[0]))
Card1.itemset(1,(ElementInfo[1]))
Card1.itemset(2,(ElementInfo[2]))
Card1.itemset(3,(ElementInfo[3]))
Card1.itemset(4,(ElementInfo[4]))
Card1.itemset(5,(ElementInfo[5]))
return str(Card1)
def AngleSolution1(self,ElementPair):
Pair = np.genfromtxt(ElementPair, dtype=int, comments='None', delimiter=', ')
row = int(Pair.size/2)
p = mp.Pool(processes=4)
result = [p.apply_async(AngleCalculateFunction().calculate, args=(Pair[i][0], Pair[i][1])) for i in range(0, int(row/4))]
Result = open('Angles.csv', "a")
Result.write('\n'.join(map(str, ((((p.get()).replace('[','')).replace(']','')) for p in result))))
Result.write('\n')
Result.close()
p.close()
由于我错误地使用多处理,因此存在某些性能问题,但这超出了本次讨论的范围。
请您参考如下方法:
你可以这样做:
#!/usr/bin/env python
import numpy as np
test_array=np.array([[99941,1,56765,56767,51785,51793,0,0,0,0],
[101150,1,59006,59005,51782,51783,0,0,0,0]])
np.savetxt("test.out",test_array, fmt='%-10s')
那应该给你这样的输出:
99941 1 56765 56767 51785 51793 0 0 0 0
101150 1 59006 59005 51782 51783 0 0 0 0
%-10s 部分指定该列的宽度应为 10 个字符,并用空格填充其余字符。一点警告:这会在每一行的末尾打印很多额外的空格。
