是否有一种可取的方法来仅获取数据帧切片中的索引? 换句话说,是否有更好的方式编写以下代码:
df.loc [df ['A']> 5] .index
谢谢!
答案 0 :(得分:5)
是的,最好只过滤索引值,而不过滤所有DataFrame,然后选择索引:
#filter index
df.index[df['A'] >5]
#filter DataFrame
df[df['A'] >5].index
性能上也有差异:
np.random.seed(1245)
df = pd.DataFrame({'A':np.random.randint(10, size=1000)})
print (df)
In [40]: %timeit df.index[df['A'] >5]
208 µs ± 11.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [41]: %timeit df[df['A'] >5].index
428 µs ± 6.42 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [42]: %timeit df.loc[df['A'] >5].index
466 µs ± 40.1 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
如果性能很重要,请使用numpy
-将values
的索引和列的值转换为numpy数组:
In [43]: %timeit df.index.values[df['A'] >5]
157 µs ± 8.71 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
In [44]: %timeit df.index.values[df['A'].values >5]
8.91 µs ± 196 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)