熊猫在同一列中设置美元金额和百分比

时间:2021-07-21 09:35:13

标签: python pandas pandas-styles

我正在尝试附加一个应该显示带有美元金额的值的熊猫 DF 和另一个 DF 以显示百分比值(美元值的划分)

DF1:

enter image description here

DF2:

enter image description here

如果我将 DF 分开,我可以正确格式化列,但在附加时失败,并将所有列格式化为 $ 或 %。
我正在使用以下代码,并想了解如何通过“描述”列值定义子集?

opps[(opps['Name'] == name) & (opps['Description'] != 'Win Rate')].iloc[:,4:].reset_index(drop=True)\
.replace([np.inf, -np.inf], 0, regex=True)\
.append(opps[(opps['Name'] == name) & (opps['Description'] == 'Win Rate')].iloc[:,4:]).reset_index(drop=True)\
.replace([np.inf, -np.inf], 0, regex=True)\
.style\
.set_table_styles(styles)\
.format("{:.0%}", na_rep="-", subset=['YTD#'])

谢谢

1 个答案:

答案 0 :(得分:0)

使用pandas IndexSlice,或仅以(行,列)格式表示数据:

df = pd.DataFrame([[1,2],[3,4]], index=["a", "b"], columns=["c", "d"])
df.style.format("{:.3f}", subset=("a", slice(None)))

       c     d
a  1.000 2.000
b      3     4

或者,如果不使用索引来索引而是基于列值,则创建一个行布尔索引器:

df.style.format("{:.3f}", subset=(df["c"]==3, slice(None)))

       c     d
a      1     2
b  3.000 4.000