首页 > 解决方案 > 使用 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)

标签: pythonnumpy

解决方案


推荐阅读