Change the color of text within a pandas dataframe html table python using styles and css

前端 未结 2 1459
旧时难觅i
旧时难觅i 2020-11-27 06:19

I have a pandas dataframe:

arrays = [[\'Midland\', \'Midland\', \'Hereford\', \'Hereford\', \'Hobbs\',\'Hobbs\', \'Childress\',
           \'Childress\', \'R         


        
2条回答
  •  离开以前
    2020-11-27 06:35

    Using pandas new styling functionality (since 0.17.1):

    import numpy as np
    import pandas as pd
    
    arrays = [['Midland', 'Midland', 'Hereford', 'Hereford', 'Hobbs','Hobbs', 'Childress',
               'Childress', 'Reese', 'Reese', 'San Angelo', 'San Angelo'],
              ['WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS','WRF','MOS']]
    tuples = list(zip(*arrays))
    index = pd.MultiIndex.from_tuples(tuples)
    df = pd.DataFrame(np.random.randn(12, 4), index=arrays,
                      columns=['00 UTC', '06 UTC', '12 UTC', '18 UTC'])
    
    
    def highlight_MOS(s):
        is_mos = s.index.get_level_values(1) == 'MOS'
        return ['color: darkorange' if v else 'color: darkblue' for v in is_mos]
    
    s = df.style.apply(highlight_MOS)
    s
    

提交回复
热议问题