<p>解决此问题的更标准方法是构建样式的数据框架,可以使用<a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.loc.html" rel="nofollow noreferrer">^{<cd1>}</a>+<a href="https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html" rel="nofollow noreferrer">^{<cd2>}</a>根据行星在列表中的位置动态构建这些样式:</p>
<pre><code>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)
</code></pre>
<p><a href="https://i.stack.imgur.com/fPCzm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fPCzm.png" alt="styled table"/></a></p>
<hr/>
<p>示例数据和导入:</p>
<pre><code>import pandas as pd
df = pd.DataFrame({
'planet': ['Mercury', 'Venus', 'Earth',
'Mars', 'Jupiter', 'Saturn'],
'data': [1, 2, 3, 4, 5, 6]
})
</code></pre>