在字典Python中为多个numpy数组格式化print语句



我试图修改下面for循环内的print语句,以便它通过列表和字典迭代,并打印第一和第二个numpy数组的值。按照Timeframes清单。如何修改下面的print语句以获得下面的预期输出?

import numpy as np
Timeframes = ['Entirety:', 'Last Month:', 'Three Months:', 'Six Months:', 'Last Year:', 'Last Two Years:']
values = {[np.array([777.2062628 ,97.44704834 , 77.2062628 , 73.2062628 , 65.28 ,
88.22628]), np.array([31040.02425794,   115.31287155,   115.31287155,   232.78473351,
437.44961679,  4152.56739805])]}
for timeframe, values[0] in zip(Timeframes, iterator):
print(f'{timeframe:<23} ${round(iterator[0][recordcounter],2):<15}${round(iterator[1][recordcounter],2):<14}')

预期输出:

Entirety:               $777.2062628      $31040.02425794     
Last Month:             $97.44704834      $115.31287155          
Three Months:           $77.2062628       $115.31287155          
Six Months:             $73.2062628       $232.78473351         
Last Year:              $65.28            $437.44961679         
Last Two Years:         $88.22628         $4152.56739805 

如果您将时间帧设置为具有相同深度的numpy对象,则可以将数组堆叠在一起(或简单地将它们一起输入)。

在这种情况下,我们使用vstack和转置。

首先将数组堆叠在一起:

import numpy as np
Timeframes = np.array([['Entirety:', 'Last Month:', 'Three Months:', 'Six Months:', 'Last Year:', 'Last Two Years:']])
values = np.array([[777.2062628 ,97.44704834 , 77.2062628 , 73.2062628 , 65.28 ,
88.22628], [31040.02425794,   115.31287155,   115.31287155,   232.78473351,
437.44961679,  4152.56739805]])
data=np.vstack((Timeframes,values))

数据现在是:

[['Entirety:' 'Last Month:' 'Three Months:' 'Six Months:' 'Last Year:'
'Last Two Years:']
['777.2062628' '97.44704834' '77.2062628' '73.2062628' '65.28'
'88.22628']
['31040.02425794' '115.31287155' '115.31287155' '232.78473351'
'437.44961679' '4152.56739805']]

数据。T =

[['Entirety:' '777.2062628' '31040.02425794']
['Last Month:' '97.44704834' '115.31287155']
['Three Months:' '77.2062628' '115.31287155']
['Six Months:' '73.2062628' '232.78473351']
['Last Year:' '65.28' '437.44961679']
['Last Two Years:' '88.22628' '4152.56739805']]

最后,我们可以对转置的数据执行一个简单的循环:

for line in data.T:
print(line[0],line[1],line[2])

这给了我们:

Entirety: 777.2062628 31040.02425794
Last Month: 97.44704834 115.31287155
Three Months: 77.2062628 115.31287155
Six Months: 73.2062628 232.78473351
Last Year: 65.28 437.44961679
Last Two Years: 88.22628 4152.56739805
注意,您可以使用一个简单的辅助函数进一步格式化输出:
def format_as_money(num):
return '$'+str(round(float(num),2))

然后你可以编辑你的打印语句行:

for line in data.T:
print(line[0],format_as_money(line[1]),format_as_money(line[2]))

给了:

Entirety: $777.21 $31040.02
Last Month: $97.45 $115.31
Three Months: $77.21 $115.31
Six Months: $73.21 $232.78
Last Year: $65.28 $437.45
Last Two Years: $88.23 $4152.57

最新更新