gpt4 book ai didi

python - 如何使用 pandas 更改数据框中文本的字体大小

转载 作者:行者123 更新时间:2023-12-01 06:44:42 27 4
gpt4 key购买 nike

我研究了 pandas 的样式文档,但无法准确地得到我的问题的特定和精确的答案。我正在使用数据帧读取 Excel 文件并在程序中处理该数据帧。最后,我使用 xlwings 库在另一个现有的 Excel 文件中写入处理后的数据帧。

我正在使用-

import pandas as pd
import xlwings as xw
df = pd.read_excel("file.xlsx")

.
. #Code for processing dataframe and writing dataframe in another excel file
.

在另一个现有的 Excel 中写入此数据框之前,我想更改最终数据框中整个文本的字体大小。我无法找到方法来做到这一点。

我在 pandas 样式文档中找到了以下代码来实现它 -

def magnify():
return [dict(selector="th",
props=[("font-size", "4pt")]),
dict(selector="td",
props=[('padding', "0em 0em")]),
dict(selector="th:hover",
props=[("font-size", "12pt")]),
dict(selector="tr:hover td:hover",
props=[('max-width', '200px'),
('font-size', '12pt')])
]

我在我的程序中使用了上面的代码,但我的数据框的字体大小保持不变。它对字体大小没有影响。我也尝试了一些其他使用样式的方法,但字体大小保持不变。

任何人都可以以非常简单的方式告诉我如何使用 pandas 或任何其他库仅更改最终数据框的字体大小。因为我尝试了很多方法,但没有一种方法适合我。我只想更改字体大小,不想对我的字体做更多样式。

最佳答案

您可以使用set_properties()为每个单元格设置一个或多个属性。 .

df = pd.DataFrame({
'date': ('2019-11-29', '2016-11-28'),
'price': (0, 1),
})

df = df.style.set_properties(**{
'background-color': 'grey',
'font-size': '20pt',
})
df.to_excel('test.xlsx', engine='openpyxl')

您还可以使用apply()方法来自定义特定单元格:

def custom_styles(val):
# price column styles
if val.name == 'price':
styles = []
# red prices with 0
for i in val:
styles.append('color: %s' % ('red' if i == 0 else 'black'))
return styles
# other columns will be yellow
return ['background-color: yellow'] * len(val)


df = pd.DataFrame(...)
df = df.style.apply(custom_styles)
df.to_excel('test.xlsx', engine='openpyxl')

您还可以使用按元素工作的applymap方法。您可以找到更多示例in docs .

希望这有帮助。

关于python - 如何使用 pandas 更改数据框中文本的字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284208/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com