【问题标题】:Using Pandas Style I get KeyError: "None of .... are in the [columns]使用 Pandas Style 我得到 KeyError: "None of .... are in the [columns]
【发布时间】:2020-02-14 20:50:06
【问题描述】:

我使用

构建了一个数据框
    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

这是对象和 int64 的组合。我使用代码 * pd.to_html *

构建了一个 html 文件没有问题

我有 html 文件。我想根据值为 cld_hgt 的背景涂上颜色

我用过

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) 

它给出一个错误。

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]"

我查找了一个类似的问题,但我无法找出问题所在。我有一种感觉,这可能是我正在使用的代码的语法。这是类似的问题。 KeyError: "None of [['', '']] are in the [columns]" pandas python

【问题讨论】:

    标签: python html pandas styles keyerror


    【解决方案1】:

    您应该只传递子集变量中的列名。此外,您的函数应该返回一个与您的列长度相同的列表。

    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'])
    

    【讨论】:

    • 我现在收到一个值错误。 ValueError: ('Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。', '发生在索引 cld_hgt' )
    猜你喜欢
    • 1970-01-01
    • 2022-12-12
    • 1970-01-01
    • 2021-04-01
    • 2022-12-27
    • 1970-01-01
    • 1970-01-01
    • 2021-01-12
    • 2019-06-27
    相关资源
    最近更新 更多