用styler更改样式后,解决数据框中数据无法保留四位小数

来源:互联网 发布:淘宝欧美风格女装店铺 编辑:程序博客网 时间:2024/05/22 15:10

之前数据框的数据是通过计算得出的,有那种无限循环或者无限不循环小数,举个例子,原来是0.04599999,保留思四位小数后就是0.0460,在数据框的显示就是


因为是右对齐,所以看起来很方便,但是后在jupyter中的显示要去掉索引,所以就用了pandas包中的styler,这个包中还可以用CSS来更改显示,所以可以将pandas的索引不显示,但是这样就会是之前例子提到的0.0460,这个会变成0.046,数据框的显示是右对齐的,如果显示成0.046不是0.0460,那么右对齐就不好看了,就比如这种


想到的解决办法就是,在更改显示的style之前就讲这个数据框中的数字0.0460更改为字符串,之前是计算得到保留四位小数的数据,先在原始数据框添加一列字符串格式的,再将是float格式的那一列再删除,就可以用style了。还在考虑这种处理的弊端。

部分代码附上,之前的bin_woe_df的结果是一个数据框。

最后一行display是在from IPython.display import display

        listwoestr=[]
        for i in range(len(bin_woe_df['woe'])):
            listwoestr.append('%.4f' % bin_woe_df['woe'][i])
        woestr=pd.DataFrame({'woestr':listwoestr,'woe':[bin_woe_df['woe'][i] for i in range(len(bin_woe_df['woe']))]})
        bin_woe_df=pd.merge(bin_woe_df,woestr,on='woe')
        bin_woe_df.loc[:,['woestr', 'woe']] = bin_woe_df.loc[:,['woe', 'woestr']].values
        bin_woe_df= bin_woe_df.drop('woestr', 1)
        with open ('out.html','w') as out:
            styler = bin_woe_df.style
            styler.set_table_styles([
                                   {'selector': '.row_heading',
                                    'props': [('display', 'none')]},
                                   {'selector': '.blank.level0',
                                    'props': [('display', 'none')]},         
                                   {'selector': 'td:nth-child(2)',
                                    'props': [('text-align', 'center')]}, 
                                   {'selector': 'td:nth-child(3)',
                                    'props': [('text-align', 'inherit')]},
                                   {'selector': 'td:nth-child(4)',
                                    'props': [('text-align', 'center')]},
                                   {'selector': 'td:nth-child(5)',
                                    'props': [('text-align', 'left')]}
                                   ])
        display(styler)

最后的结果就是这种,处于数据保密,我也不知道怎么展示。。


原创粉丝点击