我正在尝试处理一个excel文件,以便以后可以将每一行和每一列用于特定的操作。
我的问题如下:
#reading the excel file
path = r'Datasets/Chapter 1/Table B1.1.xlsx'
wb = load_workbook(path) #loading the excel table
ws = wb.active #grab the active worksheet
#Setting the doc Header
for h in ws.iter_rows(max_row = 1, values_only = True): #getting the first row (Headers) in the table
header = list(h)
for sh in ws.iter_rows(min_row = 1 ,max_row = 2, values_only = True):
sub_header = list(sh)
#removing all of the none Values
header = list(filter(None, header))
sub_header = list(filter(None, sub_header))
#creating a list of all the rows in the excel file
row_list = []
for row in ws.iter_rows(min_row=3): #Iteration over every single row starting from the third row since first two are the headers
row = [cell.value for cell in row] #Creating a list from each row
row = list(filter(None, row)) #removing the none values from each row
row_list.append(row) #creating a list of all rows (starting from the 3d one)
colm = []
for col in ws.iter_cols(min_row=3,min_col = 1): #Iteration over every single row starting from the third row since first two are the headers
col = [cell.value for cell in col] #Creating a list from each row
col = list(filter(None, col)) #removing the none values from each row
colm.append(col) #creating a list of all rows (starting from the 3d one)但同时(就我在文档中读到的内容而言),我无法可视化它,也无法对行或列执行直接操作。
df.iloc[2:]进行迭代以获得列表中的行,也不建议进行迭代--它不会给出相同的结果(将每一行保存在特定的列表中,因为标题将始终存在)。但是,与Openpyxl不同的是,使用像df[col1]-df[col2]这样的使用列名的方法对列进行直接操作要容易得多,这是我需要做的事情。(因为仅仅将所有列值放入列表中都不会对我起作用)因此,我的问题是,是否有一种解决方案可以只使用其中一种来完成我想做的事情,或者如果使用这两种方法都没有那么糟糕,请记住,我必须加载两次excel文件。
“事先谢谢!”
发布于 2021-11-23 07:45:01
使用openpyxl读取excel文件,然后将行加载到熊猫中是没有问题的:
pandas.DataFrame(row_list, columns=header)您说得对,使用索引迭代DataFrame非常慢,但是您还有其他选项:apply()、iterrows()、itertuples()
我还想指出的是,您的代码可能没有做您想做的事情。
list(filter(None, header))不仅没有过滤,而且过滤所有虚假的值,比如0或""。[1, None, 3]和列['a', 'b', 'c']。通过过滤None,您将得到[1, 3],它将与'a'和'b'列相关联。https://stackoverflow.com/questions/70047335
复制相似问题