我之前已经提出了问题Pandas set element style dependent on another dataframe,我有一个有效的解决方案,但现在我正在尝试将它应用于具有多索引的数据框,我收到错误,我不知道理解。
我有一个pandas df和随附的布尔矩阵。我想根据布尔矩阵突出显示df。
import pandas as pd
import numpy as np
from datetime import datetime
date = pd.date_range(start = datetime(2016,1,1), end = datetime(2016,2,1), freq = "D")
i = len(date)
dic = {'X':pd.DataFrame(np.random.randn(i, 2),index = date, columns = ['A','B']),
'Y':pd.DataFrame(np.random.randn(i, 2),index = date, columns = ['A','B']),
'Z':pd.DataFrame(np.random.randn(i, 2),index = date, columns = ['A','B'])}
df = pd.concat(dic.values(),axis=1,keys=dic.keys())
boo = [True, False]
bool_matrix = {'X':pd.DataFrame(np.random.choice(boo, (i,2), p=[0.3,.7]), index = date, columns = ['A','B']),
'Y':pd.DataFrame(np.random.choice(boo, (i,2), p=[0.3,.7]), index = date, columns = ['A','B']),
'Z':pd.DataFrame(np.random.choice(boo, (i,2), p=[0.3,.7]), index = date, columns = ['A','B'])}
bool_matrix =pd.concat(bool_matrix.values(),axis=1,keys=bool_matrix.keys())
def highlight(value):
return 'background-color: green'
my_style = df.style
for column in df.columns:
for i in df[column].index:
data = bool_matrix.loc[i, column]
if data:
my_style = df.style.use(my_style.export()).applymap(highlight, subset = pd.IndexSlice[i, column])
my_style
以上内容会引发AttributeError: 'Series' object has no attribute 'applymap'
我不明白作为系列回归的是什么。这是我正在进行子集化的单个值,此解决方案适用于非多索引df,如下所示。
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 = "D")
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)
boo = [True, False]
bool_matrix = pd.DataFrame(np.random.choice(boo, (len(date), 5),p=[0.3,.7]), index = date,columns=list('ABCDE'))
def highlight(value):
return 'background-color: green'
my_style = df.style
for column in df.columns:
for i in bool_matrix.index:
data = bool_matrix.loc[i, column]
if data:
my_style = df.style.use(my_style.export()).applymap(highlight, subset = pd.IndexSlice[i,column])
my_style
docs引用了CSS类,并说“索引标签单元格包括级别,其中k是MultiIndex中的级别”。我很明显地指出了这个错误,但我对如何继续进行了难以理解。
答案 0 :(得分:1)
有一个可运行的例子非常好。
您可以使用<select id="multi-select-demo" class="form-control" multiple name="ddlvessel" multiple="true" class="search-box-open-up" runat="server">
$(document).ready(function () {
$('.search-box-open-up').multiselect({
includeSelectAllOption: true,
buttonWidth: 250,
buttonClass: 'showhide',
nonSelectedText: 'Select Entities',
enableFiltering: true
});
});
将突出显示方法应用于整个数据框。
使用df.style.apply(..., axis=None)
和df
,试试这个:
bool_matrix
或者为了简化代码,您可以尝试:
def highlight(value):
d = value.copy()
for c in d.columns:
for r in df.index:
if bool_matrix.loc[r, c]:
d.loc[r, c] = 'background-color: green'
else:
d.loc[r, c] = ''
return d
df.style.apply(highlight, axis=None)
希望这就是你所需要的。