我有一个带有两个列的excel电子表格,我试图用以下代码将其转换为2d数组:
#!/usr/bin/python3
import openpyxl
import sys
import os
book = openpyxl.load_workbook('contact2019.xlsx')
sheet = book.active
first_sheet = book.get_sheet_names()[0]
worksheet = book.get_sheet_by_name(first_sheet)
excel_data = [[0 for x in range(2)] for y in range(1)]
print(len(excel_data))
first = 0
cell_num = 0
for row in range(2,worksheet.max_row+1):
for column in "AB": #Here you can add or reduce the columns
cell_name = "{}{}".format(column, row)
excel_data.append(worksheet[cell_name].value)
print(excel_data)我的问题是,数据只是按顺序添加到一个一维数组中,所以我的输出如下:
['Sam Adams', '*******@gmail.com']这不是我初始化的2d数组。
输入数据如下:
Sam Adams **********@gmail.com
Sammy Adams **********@gmail.com
Samuel Adams **********@gmail.com
Samantha Adams **********@gmail.com
Sam Adams **********@gmail.com为什么这是按顺序分配数据,而不是每一行分配两个数据?
发布于 2019-10-07 17:38:28
欢迎来到这里!
下面的代码迭代并将每个项作为一个单独的项添加,因此您可以按顺序顺序获得所有内容。
for row in range(2,worksheet.max_row+1):
for column in "AB": #Here you can add or reduce the columns
cell_name = "{}{}".format(column, row)
excel_data.append(worksheet[cell_name].value)与其先遍历行,然后遍历所有列,不如将代码替换为只循环行。
for row in range(2,worksheet.max_row+1):
excel_data.append([worksheet["A{}".format(row)].value,worksheet["B{}".format(row)].value])通过这样做,您现在正在创建一个包含2个元素列表(或一个2d数组)的列表。
如果您不打算这样做,您还可以考虑python库pandas,它抽象出大量工作,并允许您像DataFrames对象一样处理电子表格。
发布于 2019-10-07 17:46:25
或者:使用pandas
read_excelto_numpy中处理数据更容易。
import pandas as pd
import numpy as np
df = pd.read_excel('test.xlsx') # change the name of the file as needed
# dataframe
name email
Sam Adams **********@gmail.com
Sammy Adams **********@gmail.com
Samuel Adams **********@gmail.com
Samantha Adams **********@gmail.com
Sam Adams **********@gmail.com创建数组:
excel_data = df.to_numpy()
print(excel_data)
# Output
array([['Sam Adams', '**********@gmail.com'],
['Sammy Adams', '**********@gmail.com'],
['Samuel Adams', '**********@gmail.com'],
['Samantha Adams', '**********@gmail.com'],
['Sam Adams', '**********@gmail.com']], dtype=object)https://stackoverflow.com/questions/58274244
复制相似问题