【问题标题】:Applying Pandas style between two dataframes differences在两个数据框差异之间应用 Pandas 样式
【发布时间】:2019-07-30 21:33:43
【问题描述】:

我已经看到很多关于查找两个熊猫数据帧之间差异的问题,但是在这里我试图在两个数据帧之间应用Pandas.Style 差异。鉴于这两个示例数据框,我希望将格式化程序应用于 right[1, "B"] 和 right["D"],因为它们通常不同于 left 值或 new:

left = pd.DataFrame([[1,1,1], [2,2,2]], columns=list("ABC"))
right = pd.DataFrame([[1,1,10], [2,5,10]], columns=list("ABD"))

这是我对 pandas 文档指导的格式化方法的想法

def formatter(s, new):
    if s.name not in new.columns:
        # column doesn't exist strike through entire thing
        return "color: red; text-decoration: line-through;"

    elif not s.equals(new[s.name]):
        # apply per value a comparision of the elements
        # for val in s: 
            # if val != right[val.index??]:
                return "color: red; text-decoration: line-through;"

    return "color: black;"

left.style.apply(formatter, args=(right))

我的想法是,之后我应该有类似 html 的东西:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>1</td>
      <td>1</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2</td>
      <td>2</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>1</td>
      <td style="color: red; text-decoration: line-through;">10</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2</td>
      <td style="color: red; text-decoration: line-through;">5</td>
      <td style="color: red; text-decoration: line-through;">10</td>
    </tr>
  </tbody>
</table>

【问题讨论】:

    标签: python html pandas


    【解决方案1】:

    有点不清楚你到底在哪里卡住了,但代码并不遥远。

    这可能是你所追求的:

    left = pd.DataFrame([[1,1,1], [2,2,2]], columns=list("ABC"))
    right = pd.DataFrame([[1,1,10], [2,5,10]], columns=list("ABD"))
    def formatter(s, new):
        if s.name not in new.columns:
            # column doesn't exist strike through entire thing
            return ["color: red; text-decoration: line-through;"]*len(s)
    
        elif not s.equals(new[s.name]):
            return ["color: red; text-decoration: line-through;" if v else "" for v in s == new[s.name]]
    
        return ["color: black;"]*len(s)
    
    left.style.apply(formatter, args=[right])
    

    格式化程序方法现在返回与输入相同形状的数据(根据文档)。

    正确的数据帧作为列表而不是元组传递。

    还更改了每个值比较以在它们不同时返回颜色,否则保持默认样式。

    【讨论】:

      猜你喜欢
      • 2020-03-30
      • 2021-11-28
      • 2018-07-16
      • 1970-01-01
      • 2017-05-15
      • 2018-04-18
      • 2022-11-22
      • 2019-03-18
      • 1970-01-01
      相关资源
      最近更新 更多