python - 访问 Pandas 专栏的最快方法

标签 python pandas performance dataframe

我对访问 pandas 列的各种方式之间的性能差异感到困惑。

In [1]: df = pd.DataFrame([[1,1,1],[2,2,2]],columns=['a','b','c'])

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

In [3]: %timeit df.a
The slowest run took 5.14 times longer than the fastest. This could
mean that an intermediate result is being cached.
100000 loops, best of 3: 6.59 µs per loop

In [4]: %timeit df.loc[:,'a']
10000 loops, best of 3: 55 µs per loop

我知道最后一个变体比较慢,因为它可以设置值,而不仅仅是访问值。但为什么 df.adf['a'] 慢?无论缓存的中间结果如何,这似乎都是正确的。

最佳答案

Here是一个链接,解释了 . 访问和 [] 访问之间的区别。

另请查看文档中这些运算符的行为

getitem (对于 [])和 getattr (对于 .)方法。

. 似乎通过函数调用访问该列,因此比作为字典键值访问的 [] 花费的时间更少

关于python - 访问 Pandas 专栏的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45004573/

相关文章:

python - 如何在 Python 中修改 dbf 文件

python - 使用 Dask DataFrame 和 Pandas 高效读取 Timeseries CSV 数据目录

python - 使用 Geopandas,如何选择不在多边形内的所有点?

python - 如何在多个功能中最佳地使用 numba?

java - 堆,非堆和堆栈..垃圾收集的复杂性

python - pandas 中所有 NaN 的总和返回零?

python-3.x - 根据条件截断 pandas 数据帧字符串列中的条目

python - 如何循环数据框中的列表?

java - 将元素添加到根据其成本递增自动正确的位置,并获得最佳性能

jquery - 使用python中的pyquery删除html中的所有隐藏元素