gpt4 book ai didi

python - Pandas 索引器方法和元组作为参数

转载 作者:行者123 更新时间:2023-11-28 22:37:48 25 4
gpt4 key购买 nike

假设我有一个 pandas Series,我想访问特定索引处的一组元素,如下所示:

In [1]:
from pandas import Series
import numpy as np

s = Series(np.arange(0,10))

In [2]: s.loc[[3,7]]

Out[2]:
3 3
7 7
dtype: int64

.loc 方法接受一个list 作为这种选择的参数。 .iloc.ix 方法的工作方式相同。

但是,如果我使用 tuple 作为参数,.loc.iloc 都会失败:

In [5]: s.loc[(3,7)]
---------------------------------------------------------------------------
IndexingError Traceback (most recent call last)
........
IndexingError: Too many indexers

In [6]: s.iloc[(3,7)]
---------------------------------------------------------------------------
IndexingError Traceback (most recent call last)
........

IndexingError: Too many indexers

.ix 产生了一个奇怪的结果:

In [7]: s.ix[(3,7)]
Out[7]: 3

现在,我知道你甚至不能用原始的 python list 做到这一点:

In [27]:
x = list(range(0,10))
x[(3,7)]

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-27-cefdde088328> in <module>()
1 x = list(range(0,10))
----> 2 x[(3,7)]

TypeError: list indices must be integers or slices, not tuple

要从列表 中检索一组特定索引,您需要使用理解,as explained here .

但另一方面,使用 tuple 从 pandas DataFrame 中选择行似乎适用于所有三种索引方法。下面是一个使用 .loc 方法的例子:

In [8]:
from pandas import DataFrame
df = DataFrame({"x" : np.arange(0,10)})

In [9]:
df.loc[(3,7),"x"]

Out[9]:
3 3
7 7
Name: x, dtype: int64

我的三个问题是:

  • 为什么 Series 索引器不接受 tuple?看起来
    使用 tuple 很自然,因为所需的索引集是
    不可变的一次性参数。这是否仅仅是为了模仿 list 界面?
  • 奇怪的 Series .ix 结果的解释是什么?
  • 为什么 SeriesDataFrame 在这件事上不一致?

最佳答案

我认为第一个问题的答案是tuples 用于在MultiIndex 中定位。我认为后两个问题没有很好的答案,除了你在代码中分别暴露了一个错误和一个不一致(这并不难做到:))。所以 Series 提示是因为你没有MultiIndex 或者,更一般地说,元组的长度大于索引中的级别数。DataFrame 可能应该以相同的方式使用react,但事实并非如此。我认为最安全的方法是为 MultiIndex 保留 tuples 并使用列表/数组/系列来索引多行。作为旁注,您可以使用元组列表/数组来选择 MultiIndex 中的多行。

关于python - Pandas 索引器方法和元组作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36197842/

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