2017-05-20 21 views
0

我希望收入和支出的输出为全部美元。我已将打印选项设置为int,但我仍然收到小数点,并且无法在文档中看到如何将整个金额显示为美元。整数美元的numpy set_printoptions格式

revenue = [14574.49, 7606.46, 8611.41, 9175.41, 8058.65, 8105.44, 11496.28, 9766.09, 10305.32, 14379.96, 10713.97, 15433.50] 
expenses = [12051.82, 5695.07, 12319.20, 12089.72, 8658.57, 840.20, 3285.73, 5821.12, 6976.93, 16618.61, 10054.37, 3803.96] 

这是我的代码,但我无法格式化为全部美元。

import numpy as np 

np.set_printoptions(precision=0, formatter={'int_kind':':d'}) 
revenue_arr = np.array(revenue) 
expense_arr = np.array(expense) 

profits = revenue_arr - expense_arr 
print(profits) 

结果

[ 10771. 3802. 4807. 5371. 4255. 4301. 7692. 5962. 6501. 
    10576. 6910. 11630.] 

所需的结果

[ $10771 $3802 $4807 $5371 $4255 $4301 $7692 $5962 $6501 
     $10576 $6910 $11630] 

回答

2

利润实际上是一个float数组。 您可以设置numpy的通过

np.set_printoptions(formatter={'float': lambda x: '${:.0f}'.format(x)}) 

输出打印的美元符号:

>>> print(profits) 
[$2523 $1911 $-3708 $-2914 $-600 $7265 $8211 $3945 $3328 $-2239 $660 $11630] 

编辑:

要对美元符号的负值左负,需要稍微更复杂的格式,例如:

def dollar_formatter(x): 
    if x >= 0: 
     return '${:.0f}'.format(x) 
    else: 
     return '-${:.0f}'.format(-x) 

np.set_printoptions(precision=0, formatter={'float': dollar_formatter})