格式化字典中多个 numpy 数组的打印语句 Python

Formatting the print statement for multiple numpy arrays inside a dictionary Python

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

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:               7.2062628      040.02425794     
Last Month:             .44704834      5.31287155          
Three Months:           .2062628       5.31287155          
Six Months:             .2062628       2.78473351         
Last Year:              .28            7.44961679         
Last Two Years:         .22628         52.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']]

data.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: 7.21 040.02
Last Month: .45 5.31
Three Months: .21 5.31
Six Months: .21 2.78
Last Year: .28 7.45
Last Two Years: .23 52.57