如何使用pandas从excel文件中读取特定行

时间:2015-06-04 13:35:35

标签: python pandas

我有一个excel文件,我需要从某个工作表的行中提取某些数据。到目前为止我已经

import pandas as pd
xl_file = pd.ExcelFile((xlfilePath)
dfs = {sheet_name: xl_file.parse(sheet_name) for sheet_name in xl_file.sheet_names} 

现在我想读一下特定行中的数值。行结构类似于:

Length (mm) 10.1 - 16.0 - 19.5 - 16.4 - 11.3

我试图显示行的每个单元格中的内容。破折号表示单元格中的空条目!如何使用pandas库读取这样的行?我碰巧知道上面一行有哪些行号,但是pandas有没有办法查看数据框并查找条目length (mm)而不必指定行号?

编辑:EdChum建议的实际df.loc ['length(mm)']如下所示:

0              17.92377
Unnamed: 1          NaN
0.05           18.55764
Unnamed: 3          NaN
0.1            19.17039
Unnamed: 5          NaN
0.15            19.7507
Unnamed: 7          NaN
0.2            20.29776
Unnamed: 9          NaN
0.25           20.80492
Unnamed: 11         NaN
0.3             21.2667
Unnamed: 13         NaN
0.35           21.67687
Unnamed: 15         NaN
0.4            22.02884
Unnamed: 17         NaN
0.45            22.3156
Unnamed: 19         NaN
0.5            22.53051
Unnamed: 21         NaN
0.55           22.66691
Unnamed: 23         NaN
0.6            22.71949
Unnamed: 25         NaN
0.65           22.68477
Unnamed: 27         NaN
0.7            22.56162
Unnamed: 29         NaN
0.75           22.35258
Unnamed: 31         NaN
0.8            22.06432
Unnamed: 33         NaN
0.85            21.7079
Unnamed: 35         NaN
0.9            21.29801
Unnamed: 37         NaN
0.95           20.85419
Unnamed: 39         NaN
1                20.394
Name: length (mm), dtype: object

2 个答案:

答案 0 :(得分:1)

加载df后,您可以使用标签索引loc选择特定行:

df.loc['length (mm)']

如果你想要一个np.array,请执行:

df.loc['length (mm)'].values

答案 1 :(得分:0)

在读取文件时,您始终可以以数据框参数的形式指定列名。

import pandas as pd
fields = ['employee_name']

d_frame = pd.read_csv('data_file.csv', skipinitialspace=True, usecols=fields)
# get the required key or column name
print d_frame.keys()
# Get data from column name
print d_frame.employee_name

我认为employee_name将是您要从中获取值的列名。