python - 突出显示 MultiIndex DataFrame 上的 max/min - Pandas
问题描述
假设有一个 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 的样式)'c2'
所有列的元素'c3'
和'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
withmin
并按所有值进行比较:
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)
推荐阅读
- debian - 使用 Debian 在 docker 容器中挂载 Google Cloud Filestore
- mysql - 比较 MS SQL 和 MySQL 数据库中的数据
- javascript - 有没有一种简单的方法来来回转换这个 JSON?
- amazon-web-services - aws_sdk__WEBPACK_IMPORTED_MODULE_3__.StepFunctions 不是构造函数
- centos - 文件在 Centos 上不包含节标题
- android - 使用 Sms Retriever 时无法获取 OTP
- c# - 如何创建导航属性以在 EF 1 / .NET 3.5 中进行左连接?
- c# - 从 kendoGrid 中选择元素
- android - 如何使用匕首 2 在 Activity 类中注入具有接口作为其构造函数参数的 Presenter 类?
- ffmpeg - ffmpeg 通过 rtp 流式传输 RAW TS