循环的样式无法正常工作

2024-05-14 08:19:50 发布

您现在位置:Python中文网/ 问答频道 /正文

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

谢谢

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)

Tags: 数据名称地球dflenreturn行星color
2条回答

解决此问题的更标准方法是构建样式的数据框架,可以使用^{}+^{}根据行星在列表中的位置动态构建这些样式:

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)

styled table


示例数据和导入:

import pandas as pd

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

for循环中,如果行星不是列表中的第一个值,则立即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)

相关问题 更多 >

    热门问题