如何在 gspread-formatting 中应用列格式

发布于 2025-01-17 05:35:03 字数 1277 浏览 2 评论 0原文

我正在尝试在 gspread 的帮助下应用列格式,同时将数据框导出到谷歌表。我正在使用 format_with_dataframe 方法,但我不确定如何传递列名和列名;作为 column_formats 属性一部分的数据类型。

我在下面分享了我的代码。

from gspread_formatting import *
from gspread_formatting.dataframe import format_with_dataframe, BasicFormatter
from gspread_dataframe import get_as_dataframe, set_with_dataframe

from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())

import pandas as pd

data = [['tom', 10.1123, 0.23], ['nick', 15.3445, 0.3224], ['juli', 14.12, 0.023], ['robert', 9.0809, 0.722]]
df = pd.DataFrame(data, columns = ['Name', 'S-Mark', '%-Value'])

sh = gc.create("Test")
worksheet = gc.open("Test").worksheet("Sheet1")
set_with_dataframe(worksheet, df)

formatter = BasicFormatter(
    header_background_color=Color(0,0,0),
    header_text_color=Color(1,1,1),
    column_formats= {'S-Mark':'{:,.0f}'.format,'%-Value':'{:,.2f}'.format }
)

format_with_dataframe(worksheet, df, formatter, include_index=False, include_column_header=True)

我也分享示例输出

在此处输入图像描述

I am trying to apply column formatting while exporting the dataframe to google sheet with the help of gspread. I am using format_with_dataframe method but I am unsure on how to pass column-name & data types as part of column_formats attribute.

I have shared my code below.

from gspread_formatting import *
from gspread_formatting.dataframe import format_with_dataframe, BasicFormatter
from gspread_dataframe import get_as_dataframe, set_with_dataframe

from google.colab import auth
auth.authenticate_user()

import gspread
from oauth2client.client import GoogleCredentials

gc = gspread.authorize(GoogleCredentials.get_application_default())

import pandas as pd

data = [['tom', 10.1123, 0.23], ['nick', 15.3445, 0.3224], ['juli', 14.12, 0.023], ['robert', 9.0809, 0.722]]
df = pd.DataFrame(data, columns = ['Name', 'S-Mark', '%-Value'])

sh = gc.create("Test")
worksheet = gc.open("Test").worksheet("Sheet1")
set_with_dataframe(worksheet, df)

formatter = BasicFormatter(
    header_background_color=Color(0,0,0),
    header_text_color=Color(1,1,1),
    column_formats= {'S-Mark':'{:,.0f}'.format,'%-Value':'{:,.2f}'.format }
)

format_with_dataframe(worksheet, df, formatter, include_index=False, include_column_header=True)

I am sharing sample output as well

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文