python-3.x - 如何在 DataFrame 中共享 style.apply 结果的位置?
问题描述
如何应用我的数据框样式的结果(数据框的位置,而不是样式本身)?
例如,我将“highlight_max”样式应用于我的数据:
def highlight_max(data, color='red'):
'''
highlight the maximum in a Series or DataFrame
'''
attr = 'background-color: {}'.format(color)
#remove % and cast to float
data = data.astype(float)
if data.ndim == 1: # Series from .apply(axis=0) or axis=1
is_max = data == data.max()
return [attr if v else '' for v in is_max]
else: # from .apply(axis=None)
is_max = data == data.max().max()
return pd.DataFrame(np.where(is_max, attr, ''),
index=data.index, columns=data.columns)
import numpy as np
import pandas as pd
aa = pd.DataFrame([[1,2], [3,4], [1,9]])
aa.style.apply(highlight_max)
我想保留突出显示的单元格的位置并将其应用于另一个数据框,例如:
bb = pd.DataFrame([[7,3], [1,6], [4,2]])
bb.style.apply(**_Same_location_with_aa_**)
是否有任何样式选项可以获得此结果?任何意见,将不胜感激。
解决方案
据我了解,您无法导出样式格式,因为它将样式应用于第二个数据帧的最大索引。相反,您可以使用等于最大值的第一个数据帧的掩码并将其传递到函数下,np.where
如下所示:
def myf(x,color='red'):
'''
highlight based on the indices passed
'''
attr = 'background-color: {}'.format(color)
return pd.DataFrame(np.where(mask,attr,''),index=x.index,columns=x.columns)
mask = aa.eq(aa.max())
display(aa.style.apply(myf,axis=None))
display(bb.style.apply(myf,axis=None))
推荐阅读
- spring-integration - 如果我们在 Spring Integration 中的 Splitter 和 Aggregator 或接收者列表路由器和 Aggregator 之间有异常,请了解如何清理存储
- sql - 这个嵌套查询的结构有什么问题?
- python - 迭代单击包含链接的表格单元格,并在使用 selenium 和 python 抓取数据时通过链接文本找到它
- c# - C# 中 Predicate 和 Func 委托之间的区别
- ruby-on-rails - Rails link_to 调用的多个数据集和类型
- python - 如何使用 requests_html 获取网站信息?
- python - 如何在多个字符串中查找与列表中的项目匹配的项目
- c# - 如何抑制具有 Inject 属性的属性的 Resharper 广泛分析警告?
- sql - ORACLE SQL:查找最后一个最小和最大连续周期
- ios - iOS - 使用 scrollViewDidZoom 和 touchesMoved 在滚动视图上添加两指手势