Gspread 在 Google Sheets 上创建带有索引和列的数据透视表

问题描述 投票:0回答:1

我正在下面运行这段代码,

sh = gc.open_by_url('..........')
worksheet = sh.worksheet('Sheet1')
worksheet.update([df2.columns.values.tolist()] + df2.values.tolist()+df2.index.values.tolist())

df2 是一个多索引数据透视表,运行此代码仅写入值和列,但不包括 Google 表格上的索引。有没有办法包含索引并能够更改 Google 表格上的标题格式?

python gspread
1个回答
0
投票

我遇到了类似的问题并使用配套库解决了这个问题gspread_pandas

问题:

gspread
和 google Sheets API 之间的交换本身不支持 MultiIndex(行或列)。

具体问题:

有没有办法包含索引并能够更改 Google 表格上的标题格式?

解决方案:

gspread_pandas.Spread.dt_to_sheet()
方法,其参数用于修改 MultiIndex 行和列的处理方式。这包括一系列布尔标志

  • 包括/排除索引、列
  • 合并/不合并多索引行和列
  • 为标题或索引添加冻结窗格

应用于所提供代码的解决方案:

原始代码

sh = gc.open_by_url('..........')
worksheet = sh.worksheet('Sheet1')
worksheet.update([df2.columns.values.tolist()] + df2.values.tolist()+df2.index.values.tolist())

修改代码

# Import the gspread_pandas 'Spread' module
from gspread_pandas import Spread

# Using the same credentials used for gspread.authorize(credentials)
sh = Spread(spread='https://...spreadsheet_url...', creds=credentials)
sh.df_to_sheets(df=df2, # Your dataframe
                sheet='Sheet 1',  # Target sheet name
                start='A1', # First cell to place the data in
                index=True, # Show the index
                headers=True, # Show the columns
                merge_headers=True, # Merge the cells of multiindex headers
                merge_index=True, # Merge the rows of the muliindex index
                freeze_headers=True, # Freeze the header rows
               )
© www.soinside.com 2019 - 2024. All rights reserved.