python - 在 pandas 中使用 bool 数组索引对象的最惯用方法是什么?

标签 python pandas

我特别谈论 Pandas 版本 0.11,因为我正忙于用 .loc 或 .iloc 替换我对 .ix 的使用。我喜欢这样一个事实,即区分 .loc 和 .iloc 表明我是打算按标签还是按整数位置进行索引。我看到其中任何一个也会接受 bool 数组,但我希望保持它们的用法纯粹以清楚地传达我的意图。

最佳答案

在 11.0 中所有三种方法都有效,方式 suggested in the docs就是简单地使用df[mask]。然而,这不是在位置上完成的,而是纯粹使用标签,所以在我看来 loc 最能描述实际发生的事情。

更新:我在 github 上询问过关于这一点,结论是 df.iloc[msk] 将给出一个 NotImplementedError(如果是整数索引掩码)或 ValueError(如果不是pandas 11.1 中的整数索引)。

In [1]: df = pd.DataFrame(range(5), list('ABCDE'), columns=['a'])

In [2]: mask = (df.a%2 == 0)

In [3]: mask
Out[3]:
A     True
B    False
C     True
D    False
E     True
Name: a, dtype: bool

In [4]: df[mask]
Out[4]:
   a
A  0
C  2
E  4

In [5]: df.loc[mask]
Out[5]:
   a
A  0
C  2
E  4

In [6]: df.iloc[mask]  # Due to this question, this will give a ValueError (in 11.1)
Out[6]:
   a
A  0
C  2
E  4

也许值得注意的是,如果您提供掩码整数索引,它将引发错误:

mask.index = range(5)
df.iloc[mask]  # or any of the others
IndexingError: Unalignable boolean Series key provided

这表明 iloc 实际上并未实现,它使用的是标签,因此当我们尝试此操作时 11.1 会抛出 NotImplementedError

关于python - 在 pandas 中使用 bool 数组索引对象的最惯用方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16603765/

相关文章:

python - np.where( ) 不改变所有的值

python - 如何使用新值更新列的特定 DataFrame 切片?

python - 如何用绝对坐标定位Kivy Popup?

python - pip:证书失败,但 curl 有效

python - 复选框检测opencv

python - 子流程调用中的用户输入?

python - 检查.getmembers 的顺序?

python - Pandas:从带有字符串的列创建词云

python - 删除满足条件的子系列(数据框中的行)

python - Pandas mul 密集与稀疏