[英]Formatting a numpy array as aligned text columns
我想設置寫入文本文件的 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 個字符,並用空格填充其余字符。 一點警告:這會在每一行的末尾打印很多額外的空格。
np.savetxt
格式化一行,並將其寫入一個打開的文件。
In [536]: x
Out[536]:
array([[ 99941, 1, 56765, 56767, 51785, 51793, 0, 0,
0, 0],
[101150, 1, 59006, 59005, 51782, 51783, 0, 0,
0, 0]])
實際上,它正在做(使用打印而不是用於說明目的的文件寫入):
In [537]: fmt=' '.join(['%8d']*x.shape[1])
In [538]: for row in x:
print(fmt%tuple(row))
.....:
99941 1 56765 56767 51785 51793 0 0 0 0
101150 1 59006 59005 51782 51783 0 0 0 0
或者,如果您想收集一個字符串中的所有行,您可以將它們附加到一個列表中:
In [544]: astr = []
In [545]: for row in x:
astr.append(fmt%tuple(row))
.....:
In [546]: print('\n'.join(astr))
99941 1 56765 56767 51785 51793 0 0 0 0
101150 1 59006 59005 51782 51783 0 0 0 0
Python 對象顯示( str(...)
)通常會執行這種行追加和連接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.