Pandas set element style dependent on another dataframe

感情迁移 提交于 2019-12-13 12:42:53

问题


As I was writing this question I figured out an implementation. I have decided to still post it because styling is relatively new and there aren't that many questions yet so I hope it may prove useful to someone else. I am hoping to not get any downvotes and will be happy to accept someone else's implementation. I read through this post in meta and this post, so hope I am in the clear. I can provide my implementation below if desired.

I have an hourly time series that I group by daily mean. I want to highlight cells in the grouped data if a value in the hourly data meets some threshold.

For example if my daily mean is 1 and my threshold is values < -1, I want to highlight the daily means that had an hourly value below -1.

My Hourly Data:

import pandas as pd
import numpy as np
from datetime import datetime
np.random.seed(24)
date = pd.date_range(start = datetime(2016,1,1), end = datetime(2016,2,1), freq = "H")
df = pd.DataFrame({'A': np.linspace(1, 100, len(date))})
df = pd.concat([df, pd.DataFrame(np.random.randn(len(date), 4), columns=list('BCDE'))],
               axis=1)

df['date'] = date
df.set_index("date", inplace = True)


#My grouped data
day = df.groupby(pd.Grouper(freq='D')).mean()

Do some stuff and then Result:


回答1:


I am going to answer my own question, but what I have is slow, which is not a deal breaker because I do not have to do it on much data, but if a better solution exists I would gladly accept that answer.

value = -1.06
grouped = df.groupby(pd.Grouper(freq= 'D'))
def highlight(val):
    return 'background-color: green' 
my_style = day.style
for column in day.columns:
    for i in day[column].index:
        data = grouped.get_group(i)[column]
        if (data<value).any(): 
            my_style = day.style.use(my_style.export()).applymap(highlight, subset = pd.IndexSlice[i,column])

my_style


来源:https://stackoverflow.com/questions/47912420/pandas-set-element-style-dependent-on-another-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!