gpt4 book ai didi

python - python 系列的层次结构索引中 x[1,2] 和 x[1][2] 有什么区别?

转载 作者:太空宇宙 更新时间:2023-11-03 10:57:43 25 4
gpt4 key购买 nike

我有一个系列

x=pd.Series(np.random.random(16),index=[[1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4],['a','b','c','d','a','b','c','d','a','b','c','d','a','b','c','d']]) 

看起来像这样:

1  a   -0.068167
b -1.036551
c -0.246619
d 1.318381
2 a -0.119061
b 0.249653
c 0.819153
d 1.334510
3 a 0.029305
b -0.879798
c 1.081574
d -1.590322
4 a 0.620149
b -2.197523
c 0.927573
d -0.274370
dtype: float64

x[1,'a'] 和 x[1]['a'] 有什么区别。它给了我同样的答案。我对内部差异意味着什么感到困惑?什么时候使用以上两个指标?

最佳答案

此解释来自numpy docs ,但是我相信 pandas 中也发生了类似的事情(它在内部使用 numpy,使用“索引器”提供(可能)命名索引和基于整数的基础索引之间的映射)。

So note that x[0,2] = x[0][2] though the second case is less efficient as a new temporary array is created after the first index that is subsequently indexed by 2.

这是您的系列节目的时间安排;第一种方法大约快 30 倍:

In [79]: %timeit x[1, 'a']
100000 loops, best of 3: 8.46 µs per loop

In [80]: %timeit x[1]['a']
1000 loops, best of 3: 274 µs per loop

关于python - python 系列的层次结构索引中 x[1,2] 和 x[1][2] 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38689743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com