英文:
Export styled dataframe to Excel (background color)
问题
I can help you with the Chinese translation. Here is the translated text:
我想要从样式化的数据框生成一个Excel文件。具体来说,我想保留单元格的背景颜色。
[![我的样式化数据框][1]][1]
我可以使用`df.to_excel()`或`df.style.to_excel()`生成Excel文件,但背景颜色在生成过程中消失了。有没有办法保留背景颜色?
[![在此输入图片描述][2]][2]
编辑:我使用的具体代码如下:
```python
df = pd.DataFrame([
{ 'color_A_in_red': True , 'A': 1 },
{ 'color_A_in_red': False , 'A': 2 },
{ 'color_A_in_red': True , 'A': 2 },
])
def highlight(x):
c = "background-color:red"
#条件
m = x["color_A_in_red"]
#样式的数据框
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
#按条件设置列
df1.loc[m, 'A'] = c
return df1
df.style.apply(highlight, axis=None)
df.to_excel("test.xlsx")
Please note that I have retained the code part without translation as requested.
<details>
<summary>英文:</summary>
I'm looking to generate an excel file from styled dataframes. Specifically I want to keep the background colors of cells.
[![My styled dataframe][1]][1]
I can generate an excel file with df.to_excel() or df.style.to_excel(), but the background color disappears along the way. Is there any way to keep the background color?
[![enter image description here][2]][2]
[1]: https://i.stack.imgur.com/TOJe9.png
[2]: https://i.stack.imgur.com/smlYQ.png
EDIT: The specific code I used:
df = pd.DataFrame([
{ 'color_A_in_red': True , 'A': 1 },
{ 'color_A_in_red': False , 'A': 2 },
{ 'color_A_in_red': True , 'A': 2 },
])
def highlight(x):
c = f"background-color:red"
#condition
m = x["color_A_in_red"]
# DataFrame of styles
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
# set columns by condition
df1.loc[m, 'A'] = c
return df1
df.style.apply(highlight, axis=None)
df.to_excel("test.xlsx")
</details>
# 答案1
**得分**: 0
df.style.apply() 不会直接改变df,而是返回一个修改后的副本。以下代码有效:
```python
df = pd.DataFrame([
{ 'color_A_in_red': True , 'A': 1 },
{ 'color_A_in_red': False , 'A': 2 },
{ 'color_A_in_red': True , 'A': 2 },
])
def highlight(x):
c = "background-color:red"
# 条件
m = x["color_A_in_red"]
# 样式的DataFrame
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
# 根据条件设置列
df1.loc[m, 'A'] = c
return df1
df = df.style.apply(highlight, axis=None)
df.to_excel("test.xlsx")
英文:
df.style.apply() does not change df directly but returns a modified copy. The following code works:
df = pd.DataFrame([
{ 'color_A_in_red': True , 'A': 1 },
{ 'color_A_in_red': False , 'A': 2 },
{ 'color_A_in_red': True , 'A': 2 },
])
def highlight(x):
c = f"background-color:red"
#condition
m = x["color_A_in_red"]
# DataFrame of styles
df1 = pd.DataFrame('', index=x.index, columns=x.columns)
# set columns by condition
df1.loc[m, 'A'] = c
return df1
df = df.style.apply(highlight, axis=None)
df.to_excel("test.xlsx")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论