查阅了取行和列的几种常用方式:
data['列名']:取单列或多列,不能用连续方式取,也不能用于取行。
data[ i: j ]:用起始行下标(i)和终止行下标(j)取单行或者连续多行,不能用于取列。
data.loc['行名', '列名']:用对象的.loc[]方法实现各种取数据方式。
data.iloc[行下标, 列下标]:用对象的.iloc[]方法实现各种取数据方式。
最终根据实际情况选择了如下方法实现功能:
import pandas as pd
import numpy as np
import xlrd
df = pd.read_excel('file.xlsx', sheet_name=None, header=0)
sheet_name_list = df.keys()
for sheet in sheet_name_list:
df_sheet = df.get(sheet)
# 当列名重复时,使用iloc选取指定行、列
col1 = df_sheet.iloc[:, 9].values
col2 = df_sheet.iloc[:, 28].values
col3 = df_sheet.iloc[:, 32].values
update time:2022-01-27
实际应用时发现,pandas会自动处理重复列名
实例:
一个文件中有两个"备注"列
pandas会将第二个"备注"转化为"备注.1"
>>> df = pd.read_excel(r'C:\Users\sjy\Desktop\test.xlsx', sheet_name=0, header=0)
<stdin>:1: FutureWarning: Inferring datetime64[ns] from data containing strings is deprecated and will be removed in a future version. To retain the old behavior explicitly pass Series(data, dtype={value.dtype})
>>> head_line = df.columns.values
>>> head_line
array(['样本编号', '收样时间', '入库时间', '门店', '检测项目', '采样日期', '姓名', '性别',
'备注', '备注.1'],
dtype=object)