python - 使用 numpy 转置列表列表,以便可以将其上传到 gsheet
问题描述
我希望将一些数据导入谷歌表格,并使用 numpy 转置列表列表,以便将其上传到 gsheet 中。
当我运行脚本时,我收到以下错误 IndexError: index 0 is out of bounds for axis 0 with size 0
def update_sheet(ws, rows, left=1, top=2):
"""
updates the google spreadsheet with given table
- ws is gspread.models.Worksheet object
- rows is a table (list of lists)
- left is the number of the first column in the target document (beginning with 1)
- top is the number of first row in the target document (beginning with 1)
"""
# number of rows and columns
num_lines, num_columns = len(rows), len(rows[0])
# selection of the range that will be updated
cell_list = ws.range(
colrow_to_A1(left,top)+':'+colrow_to_A1(left+num_columns-1, top+num_lines-1)
)
# modifying the values in the range
for cell in cell_list:
val = rows[cell.row-top][cell.col-left]
cell.value = val
# update in batch
ws.update_cells(cell_list, value_input_option='USER_ENTERED')
# read csv into pandas to manipulate the layout and edit the column headings and remove euro symbols
df = pd.read_csv(file)
df = df.iloc[2:] # remove the first 2 rows from the dataframe
#rename the df columns as it reads them in really wierd
#df['Amount'] = df['Amount'].str[2:]
df.to_csv(file, index=False)
# read in the CSV as a list of lists
with open(file) as csvfile:
rows = csv.reader(csvfile)
res = list(map(list, zip(*rows)))
# print(*res)
# delete the first column of the transposed list of lists - this means we no longer have the headers (couldn't work out how to transpose with map, list, zip, etc.)
for row in res:
del row[0]
# use numpy to transpose the list of lists so it can be uploaded into gsheet
res2 = np.array(res).T.tolist()
res2 = np.delete(res2, (0), axis=0) # removes top row from array (title row from csv export)
res2 = res2[:-3, :] # removes last 3 rows from array (superfluous export details from export)
ws = worksheet
update_sheet(ws, res2)
解决方案
推荐阅读
- java - Springboot 下拉菜单
- java - 在android中逐行读取文件后如何在UI上显示SetText值?
- microsoft-graph-api - Planner 任务优先级的 Graph API 何时可用?
- keras - keras 模型在逐层设置预训练权重后不会学到任何东西
- html - XSL/FO:在“fo:block”上遇到无效属性:在将 html 转换为 PDF (xhmtml2fo) 时显示(没有可用的上下文信息)
- angular - 选择表单控件的数量
- scala - 无法将数组放入接受可变参数的函数参数中
- r - ggpairs中的部分cor(pcor.test)
- java - 使用 mockito 在另一个方法中模拟一个方法。基本上想模拟methodA来测试statusMethod
- javascript - 在 antd 表中的行选择中,复选框未签入反应