python - 值错误: ('Series lengths must match to compare' when Using Pandas Style

标签 python html pandas dataframe

通过使用Pandas Style ,我试图突出显示那些已使用条件格式从数据帧(如下所示)子集(按行和按列)子集的单元格:

enter image description here

例如,在对第 0 行和第 1 行以及“Adam”和“Gill”列中的单元格进行子集化后,如果这些单元格的值大于相应的目标值,我想将它们突出显示为绿色,如果小于相应的目标值,则将其突出显示为橙色。

但是,我在运行代码时不断收到以下错误:

ValueError: ('系列长度必须匹配才能比较',u'发生在索引 0')

我可以做什么来解决这个问题?

这是我的代码:

import pandas as pd

def AboveTarget(s): # For dataframe style
    green = s > df["Target"]
    orange = s < df["Target"]
    return ["background-color: #86f922" if v else "background-color: #faebde" if w else "background-color: white" for v, w in zip(green, orange)]

df = pd.DataFrame({"Adam": [99.1, 95.2, 83.1],
                   "Gill": [99.2, 96.1, 81],
                   "Louis": [60, 71.5, 99.1],
                   "Target": [99, 98, 95]
                  })

html = (df.style.\
        apply(AboveTarget, subset = pd.IndexSlice[0:1, ["Adam", "Gill"]], axis = 1)
       )

html

最佳答案

通过使用subset,您可以将切片元素传递给函数AboveTarget。与 axis=1 结合,AboveTarget 的参数 s 将是 DataFrame 中的行,即索引为 ["的 Pandas Series亚当”,“吉尔”]。您无法将其与 df["Target"] 进行比较,后者是索引为 [0,1,2] 的系列。

您需要:

import pandas as pd

def AboveTarget(s): # For dataframe style
    green = s > s["Target"]
    orange = s < s["Target"]
    return ["background-color: #86f922" if v else "background-color: #faebde"\
        if w else "background-color: white" for v, w in zip(green, orange)]

df = pd.DataFrame({"Adam": [99.1, 95.2, 83.1],
               "Gill": [99.2, 96.1, 81],
               "Louis": [60, 71.5, 99.1],
               "Target": [99, 98, 95]
              })

html = (df.style.\
        apply(AboveTarget, subset = pd.IndexSlice[0:1, ["Adam", "Gill", "Target"]], axis = 1)
       )

html

将“Target”列传递给函数并与相应的 s["Target"] 值进行比较。

关于python - 值错误: ('Series lengths must match to compare' when Using Pandas Style,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856334/

相关文章:

python - 使用类的 __new__ 方法作为工厂 : __init__ gets called twice

python - 如何在 python 中合并 mp3 和 mp4/将 mp4 文件静音并在其上添加 mp3 文件

CSS div 固定定位

javascript - 在新行中动态添加更多文本字段 (html)

python - panda read_excel index_col 似乎跳过了一行

python - Azure 函数 ModuleNotFoundError : No module named 'pandas'

python - 如何在 Python 2.7 中实现迭代函数的递归函数?

Python:如何从屏幕的一侧反弹

javascript - 向下滚动时添加到居中导航栏图标/ Logo /图像的过渡

python - pandas read_csv 函数读取一列作为核苷酸序列的 NaN