将其导出到excel时如何突出显示熊猫数据框中的整行?

时间:2019-07-01 19:27:00

标签: python excel pandas writer

我有以下格式的pandas数据框,datetime是数据框的索引:

    Datetime            Price   Volume
    21.6.2019 14:59:08  98.54   100
    21.6.2019 14:59:15  99.64   200
    21.6.2019 14:59:35  95.3    300
    21.6.2019 14:59:54  96.35   400
    21.6.2019 15:00:03  97.08   500
    21.6.2019 15:00:05  95.06   600
    21.6.2019 15:00:15  96.05   700

我需要将其导出到excel,并且在导出时我想找到给定时间最近的索引并突出显示整个对应行。因此,假设我有一个名为time = 15:00:00的变量,我希望在导出15:00:03的行时被标识并突出显示。

我尝试使用df.style,但是下面的两项尝试均无效。如果能对我做错的事情有所指导,我将不胜感激。

import datetime as dt
df=df.set_index['Datetime']
date_time=dt.datetime(15)
idx=df.loc[df.index.get_loc(date_time,method='nearest')]

date_object=idx.topydatetime()
def highlight(df,date_object):
    for x in df.index:
        if x==date_object:
            background-color='yellow'
df.style.apply(highlight(df,date_object),axis=1)

OR

def highlight(df,date_object):
    return['background-color:yellow' if x==date_object else '' for x in 
df.index]

df.style.apply(highlight(df,date_object),axis=1))

0 个答案:

没有答案