【问题标题】:Pandas style for loop not working correctly熊猫风格的循环无法正常工作
【发布时间】:2021-12-06 14:59:51
【问题描述】:

我在 Pandas 中有一个数据框,其中包含行星名称和每个行星的信息。行星名称存储在标题为“行星”的列下。我想突出显示特定行星、地球、土星和火星的行。出于某种原因,当我运行此脚本并导出为 Excel 文件时,只有 highlight_planets 列表中的第一个行星被突出显示。在这种情况下,只有地球被突出显示(土星和火星没有被突出显示)。如果我将土星移动到第一个位置并将地球移动到第二个位置,则只有土星行会在数据框中突出显示。如何突出显示我的行星列包含地球、土星或火星的所有行?

谢谢。

def highlight_sentiment(row):

    highlight_planets = ['Earth', 'Saturn', 'Mars']

    for m in highlight_planets:


        if row['planet'] == m:
           return ['background-color: yellow'] * len(row)
        else:
           return ['background-color: white'] * len(row)

df.style.apply(highlight_sentiment, axis=1)

df = df.style.apply(highlight_sentiment, axis=1)
df.to_excel("df_test.xlsx", index = False)

【问题讨论】:

    标签: python pandas highlight pandas-styles


    【解决方案1】:

    在您的for 循环中,如果行星不是您列表中的first 值,则立即return

    将最后一个return 语句移到for 循环之外,这样它只会在行星与列表中的任何 值不匹配时返回白色背景。

    def highlight_sentiment(row):
        highlight_planets = ['Earth', 'Saturn', 'Mars']
        for m in highlight_planets:
            if row['planet'] == m:
               return ['background-color: yellow'] * len(row)
        return ['background-color: white'] * len(row)
    

    顺便说一句,您可以完全避免 for 循环而只使用 in

    def highlight_sentiment(row):
        highlight_planets = ['Earth', 'Saturn', 'Mars']
        if row['planet'] in highlight_planets:
            return ['background-color: yellow'] * len(row)
        return ['background-color: white'] * len(row)
    

    【讨论】:

      【解决方案2】:

      解决这个问题的更标准的方法是构建一个样式的 DataFrame,可以使用loc + Series.isin 根据行星在列表中的位置动态构建样式:

      def highlight_sentiment(df_, highlight_planets):
          # Build DataFrame With Default Style
          styles_df = pd.DataFrame('background-color: white',
                                   index=df_.index,
                                   columns=df_.columns)
          # Update Styles based on condition
          styles_df.loc[
              df_['planet'].isin(highlight_planets), :
          ] = 'background-color: yellow'
          return styles_df
      
      
      # Pass highlight_planets as an argument to allow more flexible styles
      styler = df.style.apply(highlight_sentiment,
                              highlight_planets=['Earth', 'Saturn', 'Mars'],
                              axis=None)
      # Use styler to write to excel
      styler.to_excel("df_test.xlsx", index=False)
      


      示例数据和导入:

      import pandas as pd
      
      df = pd.DataFrame({
          'planet': ['Mercury', 'Venus', 'Earth',
                     'Mars', 'Jupiter', 'Saturn'],
          'data': [1, 2, 3, 4, 5, 6]
      })
      

      【讨论】:

      • 看到“Jupiter”而不是“Jupyter”真是太奇怪了,呵呵 :)。向我 +1!
      • 我先用了一个 y。然后我记得这是行星XD
      猜你喜欢
      • 2018-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 2021-11-21
      • 2014-12-02
      相关资源
      最近更新 更多