我使用構建數據框 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_obc0 KLAX ROUTINE 2019-10-14 00:53 1:00 260 10 -9999 VFR 10.0 9999 9999 None -99991 KLAX ROUTINE 2019-10-14 01:53 1:00 240 9 -9999 VFR 10.0 9999 9999 None -99992 KLAX ROUTINE 2019-10-14 02:53 1:00 260 6 -9999 VFR 10.0 9999 9999 None -99993 KLAX ROUTINE 2019-10-14 03:53 1:00 250 5 -9999 VFR 10.0 9999 9999 None -99994 KLAX ROUTINE 2019-10-14 04:53 1:00 240 4 -9999 VFR 10.0 9999 9999 None -99995 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]"我查了一個類似的問題,但我無法弄清楚這個問題。我有一種感覺,這可能是我正在使用的代碼的語法。這是類似的問題。
1 回答

慕慕森
TA貢獻1856條經驗 獲得超17個贊
您應該只傳遞子集變量中的列名。此外,您的函數應該返回一個與您的列長度相同的列表。
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'])
添加回答
舉報
0/150
提交
取消