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

时间:2016-03-16 16:18:26

标签: python pandas

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

    A   B
1   1   a
5   2   a
6   3   a
4   4   b
9   5   b
3   6   b

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

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

1 个答案:

答案 0 :(得分:0)

您可以使用更快iat作为iloc

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

<强>时序

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
相关问题