python - 使用 Pandas Style 我得到 KeyError: "None of .... are in the [columns]
问题描述
我使用构建数据框
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:“[['','']] 中没有一个在 [columns] 中”pandas python
解决方案
您应该只传递子集变量中的列名。此外,您的函数应该返回一个与您的列长度相同的列表。
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'])
推荐阅读
- mysql - 如果重复记录,是否可以进行 MySQL SELECT 查询来更改记录?
- javascript - 在 () -> fn 上传递对 onClick 的引用是否对性能有真正的影响?在反应
- matplotlib - 使用 matplotlib,有没有办法创建基本不等式的简单二维图
- python - 使用电子邮件收集功能制作基于 python 的网站,但在输入电子邮件时崩溃
- firebase - 如何将 firebase CLI 调试文件(即 ui-debug.log、firebase-debug.log)输出文件夹更改为单独的日志文件夹?
- powershell - “InputObject”如何为空?
- java - 是否有用于侦听音频命令的 Kotlin 或 Java 库?(想要在孩子们大喊“TRICK OR TREAT”时触发万圣节展示)
- sql - 使用 SQL 从匹配的 meta_key 中检索所有帖子
- json - 预期解码 Int 但找到了一个数组
- javascript - 在数据列表中创建间距