假设有一个 2 层 MultiIndex 数据框:
df = pd.DataFrame([['one', 'A', 100,3], ['two', 'A', 101, 4],
['three', 'A', 102, 6], ['one', 'B', 103, 6],
['two', 'B', 104, 0], ['three', 'B', 105, 3]],
columns=['c1', 'c2', 'c3', 'c4']).set_index(['c1', 'c2']).sort_index()
print(df)
看起来像这个
c3 c4
c1 c2
one A 100 3
B 103 6
three A 102 6
B 105 3
two A 101 4
B 104 0
我的目标是突出显示(使用 Pandas 的样式)所有列 'c3'
的 'c2'
元素之间的最小值(或等效的最大值)和'c4'
对于 'c1'
c3 c4
c1 c2
one A **100** **3**
B 103 6
three A **102** 6
B 105 **3**
two A **101** 4
B 104 **0**
你有什么建议吗?
我已经尝试过这个,但它是按列工作的,而不是基于索引。
def highlight_min(data):
attr = 'background-color: {}'.format(color)
if data.ndim == 1: # Series from .apply(axis=0) or axis=1
is_max = data == data.min()
return [attr if v else '' for v in is_max]
else: # from .apply(axis=None)
is_max = data == data.min().min()
return pd.DataFrame(np.where(is_max, attr, ''),
index=data.index, columns=data.columns)
df = df.style.apply(highlight_min, axis=0)
结果如下
c3 c4
c1 c2
one A **100** 3
B 103 6
three A 102 6
B 105 3
two A 101 4
B 104 **0**
最佳答案
使用GroupBy.transform
与 min
并按所有值进行比较:
def highlight_min(data):
color= 'red'
attr = 'background-color: {}'.format(color)
if data.ndim == 1: # Series from .apply(axis=0) or axis=1
is_min = data == data.min()
return [attr if v else '' for v in is_min]
else:
is_min = data.groupby(level=0).transform('min') == data
return pd.DataFrame(np.where(is_min, attr, ''),
index=data.index, columns=data.columns)
关于python - 在多索引数据帧上突出显示最大/最小值 - Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55688221/