gpt4 book ai didi

Python - 如何直接从 Smartsheets 创建 pandas Dataframe?

转载 作者:行者123 更新时间:2023-12-05 08:31:18 30 4
gpt4 key购买 nike

我不明白如何导入 Smartsheet 并将其转换为 Pandas 数据框。我想操作 smartsheets 中的数据,目前我转到 smartsheets 导出到 csv 并在 python 中导入 csv,但想消除此步骤以便它可以按计划运行。

import smartsheet
import pandas as pd

access_token ='#################'

smartsheet = Smartsheet(access_token)
sheet = smartsheet.sheets.get('Sheet 1')
pd.DataFrame(sheet)

最佳答案

这是将工作表转换为数据框的简单方法:

def simple_sheet_to_dataframe(sheet):
col_names = [col.title for col in sheet.columns]
rows = []
for row in sheet.rows:
cells = []
for cell in row.cells:
cells.append(cell.value)
rows.append(cells)
data_frame = pd.DataFrame(rows, columns=col_names)
return data_frame

从智能表创建数据框的唯一问题是对于某些列类型,cell.valuecell.display_value 是不同的。例如,联系人列将显示姓名或电子邮件地址,具体取决于使用的是哪个。

这是我在需要将数据从 Smartsheet 导入 Pandas 时使用的片段。请注意,我已经包括了垃圾收集,因为我经常处理达到或接近 200,000 个单元格限制的数十张纸。

import smartsheet
import pandas as pd
import gc

configs = {'api_key': 0000000,
'value_cols': ['Assigned User']}

class SmartsheetConnector:
def __init__(self, configs):
self._cfg = configs
self.ss = smartsheet.Smartsheet(self._cfg['api_key'])
self.ss.errors_as_exceptions(True)

def get_sheet_as_dataframe(self, sheet_id):
sheet = self.ss.Sheets.get_sheet(sheet_id)
col_map = {col.id: col.title for col in sheet.columns}
# rows = sheet id, row id, cell values or display values
data_frame = pd.DataFrame([[sheet.id, row.id] +
[cell.value if col_map[cell.column_id] in self._cfg['value_cols']
else cell.display_value for cell in row.cells]
for row in sheet.rows],
columns=['Sheet ID', 'Row ID'] +
[col.title for col in sheet.columns])
del sheet, col_map
gc.collect() # force garbage collection
return data_frame

def get_report_as_dataframe(self, report_id):
rprt = self.ss.Reports.get_report(report_id, page_size=0)
page_count = int(rprt.total_row_count/10000) + 1
col_map = {col.virtual_id: col.title for col in rprt.columns}
data = []
for page in range(1, page_count + 1):
rprt = self.ss.Reports.get_report(report_id, page_size=10000, page=page)
data += [[row.sheet_id, row.id] +
[cell.value if col_map[cell.virtual_column_id] in self._cfg['value_cols']
else cell.display_value for cell in row.cells] for row in rprt.rows]
del rprt
data_frame = pd.DataFrame(data, columns=['Sheet ID', 'Row ID']+list(col_map.values()))
del col_map, page_count, data
gc.collect()
return data_frame

这会为工作表 ID 和行 ID 添加额外的列,以便我稍后可以根据需要写回 Smartsheet。

关于Python - 如何直接从 Smartsheets 创建 pandas Dataframe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59218576/

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