对于行索引无意义的数据集,我发现按行号选择数据但同时使用列名更有用。我知道 .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 列是第二列。那么引用该单元格的最佳方式是什么?
(行名通常是过滤后的结果或更大数据集的随机样本)
最佳答案
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
关于python - 是否可以选择带有行索引和列名的 Pandas 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36041277/