【问题标题】:pandas styling dollar amounts and percentages in the same columnpandas 在同一列中设置美元金额和百分比
【发布时间】:2021-07-21 09:35:13
【问题描述】:

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

DF1:

DF2:

如果我将 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#'])

谢谢

【问题讨论】:

    标签: python pandas pandas-styles


    【解决方案1】:

    使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-09
      相关资源
      最近更新 更多