是否可以选择带有行索引和列名的 Pandas 数据框?

hur*_*ale 7 python pandas

对于具有无意义行索引的数据集,我发现按行号但同时使用列名选择数据更有用。我知道.iloc只接受行/列号(整数)并且.loc只接受名称。但是有没有一种解决方法可以同时组合行号和列名?

    A   B
1   1   a
5   2   a
6   3   a
4   4   b
9   5   b
3   6   b
Run Code Online (Sandbox Code Playgroud)

例如,我想选择第 2 行和 B 列的条目 - 我不一定知道第 2 行的行名称为 5,也不一定知道 B 列是第二列。那么引用该单元格的最佳方法是什么?

(行名通常是过滤结果或更大数据集的随机样本)

jez*_*ael 6

您可以使用更快的iatiloc

print df
    A  B
1   1  a
5   2  a
6   3  c
8   4  b
9   5  b
10  6  b

print df['B'].iat[2]
c

print df['B'].iloc[2]
c
Run Code Online (Sandbox Code Playgroud)

时间

In [266]: %timeit df['B'].iat[2]
The slowest run took 31.55 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 7.28 µs per loop

In [267]: %timeit df['B'].iloc[2]
The slowest run took 24.47 times longer than the fastest. This could mean that an intermediate result is being cached 
100000 loops, best of 3: 11.5 µs per loop
Run Code Online (Sandbox Code Playgroud)