Search code examples
pythonhtmlpandasstyleskeyerror

Using Pandas Style I get KeyError: "None of .... are in the [columns]


I build a dataframe using

    result = pd.concat([dmicao,dms,dmtime,dmdt,dmwd,dmws,dmwg,dmfc,dmvis,dmch,dmcl,dmwx,dmov], axis=1)#, sort=False)

    headers = ['icao','msg_type','time','dt','ddd','ff','gg','flt_cat','vis','cld_hgt','cld_type','present_wx','vis_obc']

    result.columns = headers

   icao msg_type              time    dt  ddd  ff    gg flt_cat   vis  cld_hgt cld_type present_wx vis_obc
0   KLAX  ROUTINE  2019-10-14 00:53  1:00  260  10 -9999     VFR  10.0     9999     9999       None   -9999
1   KLAX  ROUTINE  2019-10-14 01:53  1:00  240   9 -9999     VFR  10.0     9999     9999       None   -9999
2   KLAX  ROUTINE  2019-10-14 02:53  1:00  260   6 -9999     VFR  10.0     9999     9999       None   -9999
3   KLAX  ROUTINE  2019-10-14 03:53  1:00  250   5 -9999     VFR  10.0     9999     9999       None   -9999
4   KLAX  ROUTINE  2019-10-14 04:53  1:00  240   4 -9999     VFR  10.0     9999     9999       None   -9999
5   KLAX  ROUTINE  2019-10-14 05:53  1:00  250   5 -9999     VFR  10.0     9999     9999       None   -9999

This is a combination of objects and int64. I have build a html file no problem using code * pd.to_html *

I have the html file. I would like to color coat the background the cld_hgt depending on the value

I used

def _color_red_or_green(val):
    if val>2500: 
        color = 'red' 
    else: 
        color = 'green'
    return('color: %s' % color)

highlighted=df.style.apply(_color_red_or_green,subset=df['cld_hgt'])

with open('table.html', 'w') as f:
    f.write(highlighted.render())
    f.write(df) 

It give an error.

KeyError: "None of [Int64Index([9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 2000, 2200,\n            2200, 2200, 9999, 2500, 2500, 2700, 2600, 3000, 9999, 9999, 9999,\n            9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999,\n       9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999, 9999,\n            9999, 9999, 9999, 9999, 9999],\n           dtype='int64')] are in the [columns]"

I looked up a similar problem but I am unable to figure out the issue. I have a feeling it might be the syntax of the code I am using. Here's the similar problem. KeyError: "None of [['', '']] are in the [columns]" pandas python


Solution

  • You should pass only the column name in your subset variable. Also, your function should return a list with the same length as your column.

    def _color_red_or_green(val): 
        conditions = val > 2500
        results = [] 
        for v in conditions:
            if v:
                color = "red"
            else:
                color = "green" 
            results.append(f"color : {color}") 
        return results 
    
    highlighted=df.style.apply(_color_red_or_green,subset=['cld_hgt'])