有None值表明下面Last Month字典a中的行沒有值。我如何能夠修改 pandas 樣式格式,以便它可以列印表格a并仍然放置美元符號并在設定列的前面?
import numpy as np
import pandas as pd
a = {'Timeframes': ['Entirety:',
'Last Month:',
'Three Months:',
'Six Months:',
'Last Year:',
'Last Two Years:'],
'Compounding With Lev': np.array([2398012.89, None, 90.07, 85.29,
620.39, 30611.48], dtype=object),
'Compounding With Seperate Levs': np.array([21165662669.71, None, 91.18, 107.54,
3004.87, 13287947.75], dtype=object),
'Adjusted Long Compounding Lev': np.array([3.25, None, 1.0, 1.0, 3.5, 4.75], dtype=object),
'Adjusted Short Compounding Lev': np.array([3.75, None, 1.0, 3.0, 1.0, 2.0], dtype=object),
'Non Compounding With Lev': np.array([3626.41, None, 89.95, 95.73,
1577.75, 1380.80], dtype=object),
'Non Compounding With Seperate Levs': np.array([5679.53, None, 91.15, 408.40,
1953.53, 2530.58], dtype=object),
'Adjusted Long NonCompounding Lev': np.array([4.25, None, 1.0, 1.0, 10.5, 4.25], dtype=object),
'Adjusted Short NonCompounding Lev': np.array([7.75, None, 1.0, 33.25, 1.0, 7.75], dtype=object)}
display(pd.DataFrame(a).style.format(formatter={'Compounding With Lev': '${:,.2f}',
'Compounding With Seperate Levs': '${:,.2f}',
'Non Compounding With Lev': '${:,.2f}',
'Non Compounding With Seperate Levs': '${:,.2f}'}))
預期輸出:

uj5u.com熱心網友回復:
import numpy as np
import pandas as pd
a = {'Timeframes': ['Entirety:',
'Last Month:',
'Three Months:',
'Six Months:',
'Last Year:',
'Last Two Years:'],
'Compounding With Lev': np.array([2398012.89, None, 90.07, 85.29,
620.39, 30611.48], dtype=float),
'Compounding With Seperate Levs': np.array([21165662669.71, None, 91.18, 107.54,
3004.87, 13287947.75], dtype=float),
'Adjusted Long Compounding Lev': np.array([3.25, None, 1.0, 1.0, 3.5, 4.75], dtype=float),
'Adjusted Short Compounding Lev': np.array([3.75, None, 1.0, 3.0, 1.0, 2.0], dtype=float),
'Non Compounding With Lev': np.array([3626.41, None, 89.95, 95.73,
1577.75, 1380.80], dtype=float),
'Non Compounding With Seperate Levs': np.array([5679.53, None, 91.15, 408.40,
1953.53, 2530.58], dtype=float),
'Adjusted Long NonCompounding Lev': np.array([4.25, None, 1.0, 1.0, 10.5, 4.25], dtype=float),
'Adjusted Short NonCompounding Lev': np.array([7.75, None, 1.0, 33.25, 1.0, 7.75], dtype=float)}
display(pd.DataFrame(a).style.format(formatter={'Compounding With Lev': '${:,.2f}',
'Compounding With Seperate Levs': '${:,.2f}',
'Non Compounding With Lev': '${:,.2f}',
'Non Compounding With Seperate Levs': '${:,.2f}'}, na_rep='None'))
通過更改,dtype=float我們允許在陣列中numpy放置nan值。na_rep引數是格式化不適用時格式化程式將放置的內容。
要轉換字典a,以防您的字典像從檔案中讀取的那樣,并且陣列已經是dtype=object:
for k, v in a.items():
if isinstance(v, np.ndarray):
a[k] = v.astype(float)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/405626.html
標籤:
