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

标签 python pandas indexing hierarchy

我有一个系列

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/

相关文章:

python - Matplotlib hexbin : How to avoid displaying bins where np. 平均值为零

python - 从 parquet 读取时,dask dataframe 列重命名很慢(呃)

python - Pandas Dataframe - 过滤数据以获得唯一的最大和最小行

mysql - MySql中BETWEEN操作的索引

Python:根据匹配插入字典中的列表

Python-numpy : Specifying item size of a compound data type doesn't work

python - 如何比较python中的两个列表,对象实例

python - 字典到数据框

Python pandas,按数据框中的日期聚合值

c++ - 是否可以仅使用过滤器处理程序来扩展 Windows 搜索索引?